preface
An exception is a flow of instructions in a program that causes the program to interrupt operation. When an exception occurs, the program will interrupt directly without performing any subsequent operations! Example: Divide two numbers. If no exception is handled, the result will be displayed only if two numbers are entered correctly.
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println(" Please enter the first digit: "); String text1 = scanner.nextLine(); int x1 = Integer.parseInt(text1); System.out.println(" Please enter the second digit: "); String text2 = scanner.nextLine(); int x2 = Integer.parseInt(text2); System.out.println(x1/x2); }Copy the code
A NumberFormatException is generated when the input is not a number:
ArithmeticException is also generated when the input is all numbers but the divisor is 0:
As a programmer, don’t take it for granted that users will strictly follow your requirements to input content, if they enter a step wrong, the whole program will be interrupted, so be sure to handle exceptions! Here is the code after exception handling:
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int x1; While (true) {system.out.println (" Please enter the first digit: "); String text1 = scanner.nextLine(); try { x1 = Integer.parseInt(text1); break; } catch (NumberFormatException e) {system.out.println (" Input error, please input number!" ); } } int x2; While (true) {system.out.println (" Please enter the second number: "); String text2 = scanner.nextLine(); try { x2 = Integer.parseInt(text2); break; } catch (NumberFormatException e) {system.out.println (" Input error, please input number!" ); } } try { System.out.println(x1/x2); } catch (ArithmeticException e) {system.out.println (" Divisor cannot be 0!" ); }}Copy the code
If the input content is not a number, the system prompts you to enter the following information:
When the divisor is 0, the divisor cannot be 0:
This is called exception handling.
try-catch
If you want to handle an exception, you must use a standard processing format. The syntax of the processing format is as follows:
Catch (exception type 1 object name 1) {catch(exception type 2 object name 2) {// Exception handling operation}... Finally {// exception unified exit}Copy the code
Processing process:
1. Once an exception is generated, the system automatically generates an instantiation object of the exception class. 2. If the exception occurs in a try statement, a matching catch statement will be automatically found and executed. If the exception is not in a try statement, the exception will be thrown. 3. All catches match the instantiated object of the exception class according to the parameters of the method. If the match is successful, it means that the catch is processed.
finally:
After exception handling, there is also a finally statement in the exception handling format, which acts as a unified exit for the exception and ultimately executes the code regardless of whether an exception is raised. Finally is executed even if no exception occurs and a return statement is used ina try.
Architecture of exceptions
In Java, there is a parent class Throwable (possibly thrown). Throwable has two subclasses: 1.Error: indicates an Error. 2.Exception: generally represents all errors in the program, so the program will try… Catch handling. Exception includes the following two types, which are handled in the same way: 1. Check exception: When the program is written, the compiler automatically checks the written code. If there is a problem, the code will be red. Examples: SQLException, IOException, ClassNotFoundException, etc. 2. Unchecked exceptions: RunntimeExceptions. The compiler cannot detect exceptions in written code, and the program will report errors at runtime. For example: NullPointException, ArithmethicException, ClassCastException, ArrayIndexOutOfBundException, etc.
Points to note in multi-exception capture:
1. Catching coarser exceptions cannot precede catching thinner exceptions. 2. For convenience, you can use Exception to catch all exceptions.
Special multiple exception capture writing:
The catch (exception type 1 | exception type 2 object name) {/ / said this piece of used to handle exception types 1 and exception type 2 exception information}Copy the code
RuntimeExcepion differs from Exception:
Integer class: public static int parseInt(String text)throws an exception, but does not require a try… Catch: Because NumberFormatException is not a direct subclass of Exception, it is a subclass of RuntimeException, and if it is a subclass of RuntimeException, it means that the program can operate without using a try… Catch is handled (without flapping), and if an exception occurs, the JVM handles it. Try… The catch.
Throws keyword
The basic handling of exceptions has been mastered in the program, but there is also a throws keyword along with exceptions. This keyword is mainly used on method declarations to indicate that exceptions are not handled in the method but are handed over to the calling place. Format:
Return value Method name ()throws Exception {}Copy the code
Throw a keyword
The throw keyword means that an exception is thrown artificially in a program, because from the exception handling mechanism, all exceptions are actually thrown by an instantiation of an exception class, which can also be thrown directly by the throw. Code:
throw new Exception("");
Copy the code
Custom exception classes (Understood)
You can customize the checked Exception type by writing a class that inherits Exception and overwrites the argument constructor. To customize the runtime exception type, write a class that inherits RuntimeExcepion and overwrites the argument constructor. Such as:
Class MyException extends Exception {class MyException extends Exception {public MyException(String MSG) {super(MSG); // Call Exception with an argument constructor}}Copy the code
Custom exceptions can do a number of things, such as:
class MyException extends Exception { public MyException(String msg) { super(msg); // Text or email the maintenance staff here to tell them there is a BUG. }}Copy the code
Exception handling often meet test questions
1. Which part of the try-catch-finally can be omitted?
A: You can omit either catch or finally. You cannot omit both. Note: Omitted catch blocks are allowed in the format, but exceptions are not caught when they occur, nor are they written in development.
2. In try-catch-finally, if a catch returns, will finally be executed?
A: The code in finally executes. The execution process is as follows: 1. Calculate the returned value and store the returned value. 2. Execute the finally code block; 3. Return the stored return value. Note: 1. The return value is determined before the finally operation, and cached. No matter what changes finally makes to the value, the return value will not change. 2. Finally it is not recommended to include a return in your code because the program will exit early in the above process, meaning that the value returned is not the value ina try or catch. 3. If the JVM is stopped ina try or catch, finally is not executed. JVM: system.exit (0);
3. Output about the following code:
public class Student { public static void main(String[] args) { int studentId = test(); System.out.println(" studentId is "+studentId); } public static int test() { int studentId = 1000; try { return studentId; } catch(Exception e) { return 0; } finally { studentId=10; }}}Copy the code
The correct answer is: The student id is 1000. If studentId = 1000 and then try, then return studentId. If studentId = 1000 and then try, then finally, then studentId = 10. The final return is the original backup value, which is 1000.
4. Cases similar to the above question:
public class Student { public static void main(String[] args) { StudentId s = test(); System.out.println(" student id is "+ s.tudentid); } public static StudentId test() { StudentId s = new StudentId(); s.studentId = 1000; try { return s; } catch(Exception e) { return s; } finally { s.studentId=10; } } public static class StudentId { int studentId; }}Copy the code
The student’s student number is 10. First, s in stack memory stores the address of heap memory, s.tudentid in heap memory is 1000 initially, then execute try, will return the address of heap memory, then backup the address, then execute finally, s.tudentid in heap memory is 10. Finally, the backup address is returned, but the actual address has not changed. The value of s.tudentid is the modified 10.
The last
Thank you for reading here, the article has any shortcomings please correct, feel the article is helpful to you remember to give me a thumbs up, every day will share Java related technical articles or industry information, welcome to pay attention to and forward the article!