Trycatchblock
Trycatchblock
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Output
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
The previous statements demonstrate three catch blocks, but you can have
any number of them after a single try. If an exception occurs in the protected
code, the exception is thrown to the first catch block in the list. If the data
type of the exception thrown matches ExceptionType1, it gets caught there.
If not, the exception passes down to the second catch statement. This
continues until the exception either is caught or falls through all catches, in
which case the current method stops execution and the exception is thrown
down to the previous method on the call stack.
Open Compiler
package com.tutorialspoint;
Output
Learn Java in-depth with real-world projects through our Java certification
course. Enroll and become a certified expert to boost your career.
Catching Multiple Exceptions with Java Try and
Catch Block
Since Java 7, you can handle more than one exception using a single catch
block, this feature simplifies the code. Here is how you would do it −
Open Compiler
package com.tutorialspoint;
Output