Exception handling in Java is managed by five keywords: try, catch, throw, throws and finally.
These keywords form an interconnected subsystem.
The instructions to be monitored are inside a try block.
If an exception occurs in the try block, it will be thrown.
The code can catch and handle the exception using catch.
System exceptions are thrown automatically by the Java runtime.
To throw an exception manually, use the throw keyword.
Exceptions that come out of a method must be declared with throws.
The code that needs to be executed when exiting the try block must be placed in a finally block.
Using try and catch
The try and catch keywords are the basis of exception handling.
They work together: a catch block can only exist if there is a try block.
This is the basic format of exception handling blocks in Java.
try {
// block of code whose errors are being monitored
}
catch (TypeExceç1 obEx) {
// handler of TypeException1
}
catch (TypeExceç2 obEx) {
// handler of TypeExceç2
}
The type of exception caught by the catch block determines which block will be executed.
We can have multiple catch blocks associated with a single try block.
Only the catch that matches the exception type will be executed, the others will be ignored.
If no exceptions are thrown, the try block will be executed normally, and catch blocks will be ignored.
Since JDK 7, there is try-with-resources, which automatically manages resources as I/O streams.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3