Subscribe
Tutorial search

Java try and catch - Java tutorial


Learn how to use the try and catch statements in Java
Category: Java tutorials - Difficulty:




Using try and catch Statements

The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it.

Syntax to declare try block

try
{
   //statements that cause the exception
}

If an exception is raised within the try block, the appropriate exception-handler that is associated with it. If an exception is raised within the try block, the appropriate exception-handler that is associated with the try block processes the exception.

The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run-time error. A try block must have at least one catch block that follows it immediately. The catch clause specifies the exception type that you need to catch.

Syntax to declare try-catch block

try
{
   //statements that cause the exception
}
catch(ExceptionName obj)
{
   //error handling code
}

The catch statements takes the object of the exception class that refers to the exception caught, as a parameter. When the exception is caught, the statements within the catch block are executed. The scope of the catch block is restricted to the statements in the preceding try block only.