Java series notes --- exceptions, java series notes ---
Exception
I. Differences between exceptions and errors
Before talking about exceptions, we should know the differences between exceptions and errors.
The parent classes of the Error and Exception classes are both throwable classes. Their differences are:
Errors generally refer to problems related to virtual machines, such as system crashes, virtual machine errors, insufficient memory space, and method call stack overflow. For application interruptions caused by such errors,
The program itself alone cannot be recovered and prevented. If such an error occurs, it is recommended that the program be terminated.
The Exception class indicates the exceptions that can be handled by the program, which can be captured and possibly recovered. In case of such exceptions, try to handle the exceptions as much as possible so that the program can resume operation without terminating the exceptions at will.
Ii. Classification of exceptions:
1. checked Exception check period Exception java. lang. Excetion requires manual processing during the compilation period; otherwise, compilation fails: Exception subclasses except runtime exceptions are all checked exceptions.
2. Non-Checked exception during runtime exception java. lang. RuntimeException does not need to be processed and can be compiled directly: All RuntimeException and its subclass are running exceptions.
For example, an exception occurs during runtime.
Result: An exception occurs during the runtime. If you have typed the code, no error is returned. When you run the code, no error is returned.
For example, the check period is abnormal:
Result: An exception occurs during the check period. When compiling, an error is reported. You must throw an exception to compile the code.
Iii. Exception Handling Mechanism
The Java language mainly relies on the five keywords try catch finally and throws throw to describe the exception.
1)Handle exceptions directly
Use try catch finally to directly handle exceptions
A) In the try-catch-finally structure, try blocks are mandatory. catch and finally blocks are optional, but at least one of them must exist.
B) catch can appear at the same time, but one exception can catch at most one catch, and the catch order is from top to bottom.
C) finally: a line of code executed no matter whether an exception is caught or not.
Demo 1: try exception
1 public class TestException {2 public static void main (String [] args) {3 int c = 0; 4 try 5 {6 int a = 3; 7 int B = 0; 8 // This code has an exception 9 c = a/B; 10 // The code after the exception will not be executed 11 System. out. println ("Hello World"); 12} 13 catch (ArithmeticException e) 14 {15 System. out. println ("the divisor cannot be zero"); 16} 17 finally18 {19 // The finally statement block will be executed 20 System no matter whether an exception occurs. out. println ("Welcome"); 21} 22 System. out. println (c); 23 // when B is 0, an exception occurs. The output value is the initial value of c: 024} 25} 26 // output result: the divisor cannot be zero. Welcome 0Try exception
Demonstration 2: exceptions with return
1 import java. io. fileInputStream; 2 import java. io. fileNotFoundException; 3 public class DemoException {4 public static void main (String [] args) {5 int a = test3 (); 6 System. out. println (a); 7} 8 @ SuppressWarnings ("finally") 9 public static int test3 () {10 try {11 System. out. println (9/0); 12 return 1; 13} catch (Exception e) {14 System. out. println ("Haha"); 15 return 2; 16} finally {17 System. out. println ("Haha"); 18 return 3; 19} 20} 21} 22 // output result "Haha" "Haha" 3
Conclusion: return terminates the entire method body, but before finally appears, return is the top finally function.> return
2) throwing an exception to the caller for handling
1 // throws an exception through the declaration in the method body header... 2 public void dealFile () throws FileNotFoundException {3 FileInputStream FD = new FileInputStream ("C:/name.txt "); 4} 5 // you can choose whether to continue to throw or catch exceptions by calling this method.
Case 1: throws are used to throw an exception. The caller can directly capture the thrown exception.
1 public class TestException {2 public static void main (String [] args) {3 try {4 Test3 (); // you can directly capture exceptions here, instead of throwing an exception 5} catch (NumberFormatException e) {6 System. err. println ("non-data type cannot be converted. "); 7} // System. err. println (); this output method can output error messages in red on the console. 8} 9 10 public static void Test3 () throws NumberFormatException {11 String s = "abc"; 12 System. out. println (Double. parseDouble (s); 13} 14}Throws exception
Running result:
Non-data types cannot be converted.
Note::Throws
Two principles
Throws declaration is used to throw an exception.
Subclass inherits the parent class and overwrites the parent class
The subclass must throw fewer exceptions than the parent class.
The exception thrown by the subclass must be smaller than the parent class.
The two principles are for exceptions during the check period. Exceptions during the runtime do not follow this rule (RuntimeException and subclass)
Case 2: throw an exception
1 public class TestException {2 public static void main (String [] args) {3 String s = "abc"; 4 if (s. equals ("abc") {5 throw new NumberFormatException ("cannot be equal"); 6} else {7 System. out. println (s); 8} 9} 10}Throw exception
The running result is as follows:
Interview Questions:What is the difference between Throw and Throws?
The Throw statement is used in the method body to indicate that the thrown exception is handled by the statements in the method body.
The Throws statement Throws an exception after the method declaration, indicating that the thrown exception is handed over to the caller for processing.
Throws either use try-catch-finally to process or continue to throw
Iv. Custom exceptions
A custom Exception is usually a class that inherits the Exception class or its subclass. The Exception must be directly or indirectly inherited from the Exception class.
Generally, the Exception class is directly inherited from the Exception class, and the Exception class at runtime is not inherited.
Custom exceptions can be used to handle user logon errors and user input error prompts.
Follow these steps to create a custom exception:
Example: custom exception:
public class MyException extends Exception{ public MyException() { super(); } public MyException(String message) { super(message); }}
An Exception Handling Method
Public class ExceptionTest4 {public void method (String str) throws MyException {if (null = str) {throw new MyException ("the input String parameter cannot be null! ");} Else {System. out. println (str) ;}} public static void main (String [] args) throws MyException // Exception Handling Method 1, continuously throws {ExceptionTest4 test = new ExceptionTest4 (); test. method (null );}}
Another exception handling method:
1 public class ExceptionTest4 2 {3 4 public void method (String str) throws MyException 5 {6 if (null = str) 7 {8 throw new MyException ("the input string parameter cannot be null! "); 9} 10 else11 {12 System. out. println (str); 13} 14} 15 16 public static void main (String [] args) 17 {18 // Exception Handling Method 2, using try... catch statement 19 try20 {21 ExceptionTest4 test = new ExceptionTest4 (); 22 test. method (null); 23 24} 25 catch (MyException e) 26 {27 e. printStackTrace (); 28} 29 finally30 {31 System. out. println ("processing completed"); 32} 33 34} 35}
Finally, try-catch-finally is easy to use, but if it is abuse, it will only make the readability of the program worse. When the program reports an error, it cannot be quickly and accurately located.
If there are some areas where the write is not in place or is not perfect, I hope you can give more advice. If you have read some areas that you do not understand, you can leave a message and I will help you answer the question as soon as possible.