Java try-catch Examples

In Java, the try-catch block is used to handle exceptions in the program.

Try block:

The try block contains a set of statements where an exception can occur. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block. A try block must be followed by catch blocks or finally block or both.

Catch block :

A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in the try block, the corresponding catch block that handles that particular exception executes.

Finally block:

It is never recommended to take clean up code inside try block because there is no guarantee for the execution of every statement inside a try.

It is never recommended to place clean up code inside the catch block because if there is no exception then catch block won't be executed.

We require someplace to maintain clean up code which should be executed always irrespective of whether exception raised or not raised and whether handled or not handled such type of place is nothing but finally block. Hence the main objective of finally block is to maintain cleanup code.

Try { risky code } catch(x e) { handling code } finally { cleanup code }

class Test1 { public static void main(String[] args){ try {} catch(ArithmeticException e) {} }} Output: Compile and running successfully.

class Test2 { public static void main(String[] args){ try {} catch(ArithmeticException e) {} catch(NullPointerException e) {} } }

class Test3 { public static void main(String[] args){ try {} catch(ArithmeticException e) {} catch(ArithmeticException e) {} } }

class Test4 { public static void main(String[] args){ try {} } }

In this article, we have seen Java try-catch Examples.