Using the try Statement in Java Programming
Using the try Statement in Java Programming
Try block defines a block of statements that have exception handling. If an exception is thrown inside the try block, an optional catch block can handle declared exception types.
An optional finally block can be declared that will be executed
when execution exits the try block and catch clauses, regardless of
whether an exception is thrown or not. A try block must have at least
one catch clause or a finally block.
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block.
class Test
{
public static void main(String args[])
{
int d, a;
try { // monitor a block of code.
d = 0;
a = 2 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e) { // catch divide-by-zero error
System.out.println("Division by zero.");
}