![]() |
VOOZH | about |
A try-catch block in Java is used to handle exceptions and prevent the program from terminating unexpectedly.
Example: Handling the ArithmeticException using a simple try-catch block.
Exception caught: java.lang.ArithmeticException: / by zero I will always execute
try {
// Code that might throw an exception
} catch (ExceptionType e) {
// Code that handles the exception
}
The try block contains a set of statements where an exception can occur.
try
{
// statement(s) that might cause exception
}
The catch block is used to handle the uncertain condition of a try block. A try block must be followed by at least one catch block or a finally block. which handles the exception that occurs in the associated try block.
catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}
try{
// this will throw ArithmeticException
int ans = 10/0;} catch(ArithmeticException e) {
System.out.println("caught ArithmeticException");
} finally {
System.out.println("I will always execute whether an Exception occur or not");
}
Example: Here, we demonstrate the working try catch block with multiple catch statements.
Outer try block started Caught ArithmeticException: java.lang.ArithmeticException Caught NullPointerException: java.lang.NullPointerException Finally block executed Program continues after nested try-...