This is the 24th day of my participation in the August Text Challenge.More challenges in August
abnormal
Overview of exceptions
- Exception is abnormal meaning, Java language mainly refers to the program in the running stage of the error
- A person who is Throwable
- The java.lang.Throwable class is the superclass for all errors or exceptions in a Java program
- There are two main word classes
- Error
- Error Indicates a serious Error
- Critical errors that cannot be solved programmatically
- Exception
- Exception mainly describes lightweight errors
- It can be solved programmatically
- Error
The main classification of the Exception class
RuntimeException -> Run-time exception, also known as a non-detection exception class
- Non-detectable exception classes refer to exceptions that cannot be detected by the compiler during b compilation
- Main subclass
- ArithmeticException -> ArithmeticException class
- ArrayIndexOutOfBoundsException (indirect subclass) – > array subscript exception classes
- NullPointerException -> NullPointerException
- ClassCastException -> Type conversion exception
- NumberFormatException (indirect subclass) -> NumberFormatException
- Pay attention to
- If an exception occurs during program execution and is not handled manually, the Java VM uses the default method to handle the exception. By default, the Java VM displays the name, cause, and location of the exception and terminates the program. The subsequent code cannot be executed
IOException and Other exception classes -> Other exception classes, also known as non-detective exceptions
case
TestRuntimeException.java
package demo1;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/ * * ArithmeticException - > arithmetic exception class ArrayIndexOutOfBoundsException (indirect subclass) - > array subscript exception class NullPointerException - > null pointer exception ClassCastException -> type conversion exception NumberFormatException -> NumberFormatException */
public class TestRuntimeException {
public static void main(String[] args) {
// Observe detectability anomalies
// FileInputStream fis = new FileInputStream("c:/a.txt");
/ / Java. Lang. ArithmeticException arithmetic exception
int a = 10;
int b = 0;
if(b ! =0) {
System.out.println(a/b);
}
/ / Java. Lang. ArrayIndexOutOfBoundsException array subscript crossing the line
int[] arr = new int[3];
int num = 3;
if (num >= 0 && num < arr.length) {
System.out.println(arr[num]);
}
// java.lang.NullPointerException
String str = null;
if(str ! =null) {
System.out.println(str.length());
}
// java.lang.ClassCastException
Exception ex = new Exception();
if (ex instanceof IOException) {
IOException ie = (IOException) ex;
}
// java.lang.NumberFormatException
String s = "12be";
if (s.matches("\\d+")) {
System.out.println(Integer.parseInt(s));
}
System.out.println("End of running program"); }}Copy the code
Exception handling
How runtime exceptions are handled
- For the vast majority of runtime exceptions, exceptions can be avoided by conditional judgment
Exception catching
-
Syntax Syntax Try {block of possible exception objects}catch(exception type reference name){block of processing statements for the current exception type object}…. (can write multiple catch) finally{block of statements that should be executed regardless of whether an exception occurs}
-
Matters needing attention
- When there are multiple catch branches in the catch structure, remember that the small exception type is placed on top of the large exception type
- Lazy: catch(Exception e) {…. }
-
Execute the process
try { a; b; // possible exception statement c; } catch (Exception e) { e; } finally { f; }Copy the code
- When no exception is generated, the program runs as follows: A, B, C, and F
- When an exception occurs, the program execution flow is as follows: A, B, e, and F
-
case
- TestExceptionCatch.java
package demo2; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class TestExceptionCatch { public static void main(String[] args) { // Declare a reference to an object of this class, used to read the contents of a file FileInputStream fis = null; try { // New FileNotFoundException() fis = new FileInputStream("d:/a.txt"); } catch (FileNotFoundException e) { // Displays the name, cause, and location of the exception e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } catch (NullPointerException e) { // system.out.println (" output "); // system.out.println (" output ");e.printStackTrace(); }}}Copy the code
- TestFinally.java
package demo3; public class TestFinally { public static void main(String[] args) { int a = 10; int b = 0; try { System.out.println(a/b); } catch (Exception e) { e.printStackTrace(); return ; } finally { System.out.println("Execute regardless of whether an exception occurs."); } System.out.println("End of program"); }}Copy the code
Java. Lang. ArithmeticException: / by zero no matter whether an exception occurs will perform at demo3. TestFinally. Main (TestFinally. Java: 9)Copy the code
Exception throwing
- The basic concept
- When an exception is raised and cannot be handled directly or is not desired, it can be passed to the caller of the current method. This is called throwing an exception
- Syntax format
- Return value Type Method name (parameter list) throws exception type {…. }
- The principle of method rewriting
-
It requires the same method name, same argument list, and same return value type. Starting in JDK1.5, return subclass types are allowed
-
The scope permission cannot be smaller, but can be the same or larger
-
Larger exceptions cannot be thrown
-
Pay attention to
- A method overridden in a subclass can choose to throw the same exception as its parent, a smaller exception, no exception, but not a larger exception, or a different exception
- case
A.java “`java package demo4;
import java.io.IOException; public class A { public void show() throws IOException{ System.out.println("A"); } } ``` SubA.java ```java package demo4; import java.io.IOException; import java.io.FileNotFoundException; import javax.print.PrintException; public class SubA extends A{ @Override // public void show() throws IOException { // public void show() throws FileNotFoundException { // public void show() throws PrintException { // public void show() throws Exception { public void show() { } } ``` Copy the code
Obviously you can’t throw a larger exception
-
Custom exception
-
Custom exception origin
- The official Java library provides a large number of exception classes, but not enough to describe all real-world exceptions. When there are exceptions that are not described by M in the official library, it is necessary for programmers to define their own exception classes to describe them, making the exception information more targeted and readable
-
The process of customizing exceptions
- Custom classes inherit from the Exception class or a subclass of the Exception class
- Provides two versions of the constructor, one that takes no arguments and the other that takes strings as arguments
-
Custom exceptions — > Case 1
- Person.java
package demo5; public class Person { private String name; private int age; public Person(a) { super(a); }public Person(String name, int age) throws Exception { super(a); setName(name); setAge(age); }public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) throws Exception { if(age > 0 && age < 150) { this.age = age; } else { // system.out.println (); // system.out.println (); // Manually generate an exception object and throw it // throw new Exception(); throw new AgeException("Not a reasonable age!"); } System.out.println("Produce an abnormal effect."); } @Override public String toString(a) { return "Person [name=" + name + ", age=" + age + "]"; }}Copy the code
- AgeException.java
package demo5; public class AgeException extends Exception { / * * * * / private static final long serialVersionUID = 1L; // A custom constructor with no arguments public AgeException(a) {}// Customize the constructor that takes a string as an argument public AgeException(String msg) { super(msg); }}Copy the code
- TestPerson.java
package demo5; public class TestPerson { public static void main(String[] args) { Person p = null; try { p = new Person("Zhang", -12); } catch (Exception e) { // TODO Auto-generated catch blocke.printStackTrace(); } System.out.println(p); }}Copy the code
Demo5. AgeException: Incorrect age! null at demo5.Person.setAge(Person.java:33) at demo5.Person.<init>(Person.java:15) at demo5.TestPerson.main(TestPerson.java:8)Copy the code
-
Custom exceptions — > Case 2
- Student.java
package demo6; public class Student { private String name; private int id; public Student(a) { super(a); }public Student(String name, int id) throws IDException { super(a); setName(name); setId(id); }public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getId(a) { return id; } public void setId(int id) throws IDException { if (id > 0) { this.id = id; } else { // system.out.println (); // system.out.println (); throw new IDException("Student Number is not reasonable"); } System.out.println("The end"); } @Override public String toString(a) { return "Student [name=" + name + ", id=" + id + "]"; }}Copy the code
- IDException.java
package demo6; public class IDException extends Exception { / * * * * / private static final long serialVersionUID = 1L; public IDException(a) {}public IDException(String msg) { super(msg); }}Copy the code
- TestStudent.java
package demo6; public class TestStudent { public static void main(String[] args) throws IDException { /*Student stu = null; Try {stu = new Student("小王", -5); } catch (IDException e) { // TODO Auto-generated catch block e.printStackTrace(); } * / Student stu = new Student("Wang", -5); System.out.println(stu); }}Copy the code
Exception in thread "main" demo6.IDException: At demo6.student. setId(student.java :30) at demo6.student. <init>(student.java :14) at demo6.student. setId(student.java :30) at demo6.student. <init>(student.java :14) at demo6.TestStudent.main(TestStudent.java:14)Copy the code
One thing to note here is that in case 1, TestPerson, in the main function, we use try…. The catch statement, the exception is handled internally, and it prints the following statement whereas in TestStudent in case two, we pass the exception directly to main, which is to say, to the virtual machine, so we don’t execute the following statement
Throwing of an exception object
- Throw new exception type ()
- Such as:
-
throw new Exception()
-
Finally, a brief introduction to the difference between throws and throws
Throws and throws
- throws
- Used after the method declaration, followed by the exception class name
- Multiple exception class names can be separated by commas
- Represents an exception thrown and is handled by the caller of the method
- Throws represents a possibility of exceptions that are not necessarily expected
- throw
-
Used in the body of a method with the exception object name
-
Only one exception object name can be thrown
-
Represents a thrown exception, implemented by a statement in the method body
-
A throw throws an exception, and executing a throw must throw some kind of exception
-
Finally, welcome to pay attention to my personal wechat public account “Little Ape Ruochen”, get more IT technology, dry goods knowledge, hot news