try Statement
A try statement is used to catch exceptions that might be thrown as your program executes. You should use a try statement whenever you use a statement that might throw an exception That way, your program won’t crash if the exception occurs.
The try statement has this general form:
try
{
statements that can throw exceptions
}
catch (exception-type identifier)
{
statements executed when exception is thrown
}
finally
{
statements that are executed whether or not
exceptions occur
The statements that might throw an exception within a try block. Then you catch the exception with a catch block. The finally block is used to provide statements that are executed regardless of whether any exceptions occur.
Here is a simple example:
int a = 5;
int b = 0; // you know this won’t work
try
{
int c = a / b; // but you try it anyway
}
catch (ArithmeticException e)
{
System.out.println(“Can’t do that!”);
}
In the preceding example, a divide-by-zero exception is thrown when the program attempts to divide a by b. This exception is intercepted by the catch block, which displays an error message on the console.
Here are a few things to note about try statements:
You can code more than one catch block. That way, if the statements in the try block might throw more than one type of exception, you can catch each type of exception in a separate catch block.
In Java 7, you can catch more ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access