Exception handling
Java exception
Java uses exceptions to indicate errors and catches exceptions through
try...catch
.
- Put the code that may cause exceptions in
try {...}
, and then usecatch
to capture the correspondingException
and its subclasses.- Java’s exception is
class
and inherited fromThrowable
.Error
is a serious error that does not need to be caught, andException
is a handleable error that the error should see.
RuntimeException
does not need to be captured forcibly, non-RuntimeException
.- Checked Exception needs to be seized forcibly or declared with
throws
. - It is not recommended to catch the exception but not do any processing.
Catch the exception
When using
try ... catch ... finally
.
-
The matching order of multiple
catch
statements is very important, and the subclass must be placed first. -
The
finally
statement guarantees that it is will execute it with or without exception. It is optional. -
A
catch
statement can also match multiple non-inheritance exceptions.
Throw an exception
How to throw an exception
- Create an instance of
Exception
.- Use the
throw
statement to throw.
void process2(String s) { if (s == null) { NullPointerException e = new NullPointerException(); throw e; throw new NullPointerException(); } }
-
When catching an exception and throwing a new exception again, it should hold the original exception information;
-
Do not usually finally throw exceptions in
NullPointerException
-
NullPointerException
is a common logic error in Java code, which should be exposed and fixed early. -
You can enable the enhanced exception information of Java 14 to view the detailed error information of
NullPointerException
.