question
I encountered a problem today. In the following code, when a runtime exception is thrown, will the subsequent code still be executed? Do I need to add a return statement after the exception?
public void add(int index, E element){ if(size >= elements.length) { throw new RuntimeException("The order table is full, cannot be added"); //return; //Is it necessary? } ....}
To answer this question, I wrote a few pieces of code to test it, and the results are as follows:
//Code 1public static void test() throws Exception { throw new Exception("parameter out of bounds"); System.out.println("After exception"); //Compilation error, "Unaccessible statement"} //Code 2try{ throw new Exception("Parameter out of bounds"); }catch(Exception e) { e.printStackTrace();}System.out.println("After exception");// Can be executed //Code 3if(true) { throw new Exception("Parameter out of bounds"); }System.out.println("After exception"); //Exception is thrown, will not be executedSummarize:
If an exception is thrown before a piece of code and the exception is not caught, this piece of code will generate a compile-time error "inaccessible statement". As code 1
If an exception is thrown before a piece of code, and this exception is caught by try...catch , if no new exception is thrown in the catch statement at this time, the code can be executed, otherwise, the same as Article 1. Like code 2
If an exception is thrown in a conditional statement, the program can be compiled, but the subsequent statements will not be executed. As code 3
Also summarize the difference between runtime exception and non-runtime exception:
Runtime exceptions are exceptions of RuntimeException class and its subclasses, and are non-checked exceptions, such as NullPointerException , IndexOutOfBoundsException , etc. Since such exceptions are either system exceptions and cannot be handled, such as network problems;
Either it is a program logic error, such as a null pointer exception; the JVM must stop running to correct this error, so the runtime exception can be handled without processing (catching or throwing up, of course, it can also be handled) and the JVM handles it itself. Java Runtime will automatically catch to RuntimeException of the program throw , then stop the thread and print the exception.
Non-runtime exceptions are exceptions other than RuntimeException . They all belong to Exception class and its subclasses in type, and are checked exceptions. Non-runtime exceptions must be processed (catching or throwing up) and if not processed, the program will have a compile error. Generally speaking, Exception written in the API that throws is not RuntimeException .
Common runtime exceptions:
Common non-runtime exceptions:
Okay, the above is the entire content of this article. I hope the content of this article will be of some help to everyone’s study or work. If you have any questions, you can leave a message to communicate.