In Java, the try-catch
block is used to handle exceptions that may be thrown during the execution of a program.
Here is an example of how you can use a try-catch
block in Java:
try { // code that may throw an exception goes here } catch (ExceptionType1 e1) { // handling code for ExceptionType1 goes here } catch (ExceptionType2 e2) { // handling code for ExceptionType2 goes here } finally { // code that will always be executed goes here }
The try
block contains the code that may throw an exception. If an exception is thrown, the exception is caught by the appropriate catch
block, which contains code to handle the exception. The finally
block contains code that will always be executed, regardless of whether an exception is thrown or not.
For example, consider the following code that divides two numbers and handles the ArithmeticException
that may be thrown if the divisor is 0:
try { int result = numerator / denominator; System.out.println(result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); }
If the divisor is not 0, the code in the try
block will be executed and the result will be printed. If the divisor is 0, an ArithmeticException
will be thrown and caught by the catch
block, which will print an error message.