Multi catch
Multi catch A multi catch block is a feature in Java that allows you to handle multiple exceptions of different types in the same catch block. This allows y...
Multi catch A multi catch block is a feature in Java that allows you to handle multiple exceptions of different types in the same catch block. This allows y...
Multi catch
A multi catch block is a feature in Java that allows you to handle multiple exceptions of different types in the same catch block. This allows you to catch a wider range of exceptions and handle them in a consistent manner.
To use a multi catch block, you use the catch keyword with multiple catch clauses. Each catch clause should be followed by a throws clause that specifies the type of exception that you want to handle.
For example:
java
public class MultiCatchExample {
public void main(String[] args) throws Exception {
// Throw an exception of type NullPointerException
throw new NullPointerException("The object is null");
// Throw an exception of type ArithmeticException
throw new ArithmeticException("The result is out of bounds");
}
}
Output:
Exception in 'main' at line 6
java.lang.NullPointerException: The object is null
Exception in 'main' at line 12
java.lang.ArithmeticException: The result is out of bounds
In this example, the code attempts to access a null object and throws a NullPointerException. It also attempts to perform an operation on an out-of-bounds value and throws an ArithmeticException.
The multi catch block will handle both of these exceptions and print the following output to the console:
Exception in 'main' at line 6
java.lang.NullPointerException: The object is null
Exception in 'main' at line 12
java.lang.ArithmeticException: The result is out of bounds
By using a multi catch block, you can make your code more robust and handle a wider range of exceptions