Problem
There is a problem today, in the following code, when the Run-time exception is thrown, does the following code execute, or do you need to add a statement after the exception? return
public void Add (int index, E element) {
if (size >= elements.length) {
throw new runtimeexception ("Sequential table full, cannot add") ;
Return Do you need it?
}
....
}
To answer this question, I have written several pieces of code to test it, and the results are as follows:
Code 1 public
static void Test () throws Exception {
throw new Exception ("parameter Out of Bounds");
System.out.println ("after abnormal"); Compilation error, "Unable to access statement"
}
Code 2
try{
throw new Exception ("parameter Out of Bounds");
} catch (Exception e) {
e.printstacktrace ();
}
System.out.println ("after exception");//Can be executed
Code 3
if (true) {
throw new Exception ("parameter Out of Bounds");
}
System.out.println ("after abnormal"); Throws an exception and does not execute
Summarize:
If an exception is thrown before a piece of code, and the exception is not captured, this code will produce a compile-time error "unreachable statement". such as code 1
If an exception is thrown before a piece of code, and the exception is try...catch
captured, if catch
no new exception is thrown in the statement, the code can be executed, otherwise, with 1th. such as Code 2
If an exception is thrown in a conditional statement, the program can be compiled, but subsequent statements will not be executed. such as code 3
In addition, summarize the difference between run-time and non run-time exceptions:
The run-time exception is the exception of a RuntimeException
class and its subclasses, and is a non-inspected exception, such as NullPointerException
, and IndexOutOfBoundsException
so on. Because this kind of exception is either a system exception, cannot be handled, such as network problems;
Either a program logic error, such as a null pointer exception, and the JVM must stop running to correct this error, so the run-time exception can be handled without processing (capturing or throwing up, of course), but by the JVM itself. Java Runtime
will automatically catch
go to the program throw
RuntimeException
, then stop the thread, and print the exception.
A non run-time exception is an exception, which is a RuntimeException
class and Exception
its subclasses, and is a client exception. Non-run-time exceptions must be processed (caught or thrown up), and if not handled, the program will have a compilation error. In general, nothing written in the API throws
is Exception
RuntimeException
.
Common Run-time Exceptions:
Common non-run-time exceptions:
Well, the above is the entire content of this article, I hope the content of this article for everyone to learn or work can bring some help, if you have questions you can message exchange.