In Java, you can use the try
...catch
statement to handle exceptions. The try
...catch
statement allows you to specify a block of code that may throw an exception, and a separate block of code to handle the exception if it is thrown.
Here's an example of how to use the try
...catch
statement to handle an exception in Java:
public class Main { public static void main(String[] args) { try { int x = 1; int y = 0; int z = x / y; } catch (ArithmeticException ex) { System.out.println(ex.getMessage()); } } }
In this example, an ArithmeticException
is thrown when the code inside the try
block attempts to divide by zero. The ArithmeticException
is caught in the catch
block and the exception's message is printed.
You can use the try
...catch
statement to handle any exception that may be thrown by the code inside the try
block. Just specify the exception type in the catch
block and put the code to handle the exception inside the catch
block.
You can also use the try
...catch
statement with multiple catch
blocks to handle different types of exceptions. Each catch
block must specify a different exception type and will only be executed if the corresponding exception is thrown.