How to use exception handling keywords try and catch in java
THE try BLOCK
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 first step in constructing an exception handler is to enclose the code that might throw an exception within a try block.
The general form is as shown below:
try
{
code
}
catch and finally blocks . . .
{
code
}
catch and finally blocks . . .
THE catch BLOCK
You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.
The general form is as shown below:
try
{
code
}
}
catch (ExceptionType name)
{
code
}
}
The simple example:
{
public static void main(String args[])
{
int d, a;
try
{ // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{ // catch divide-by-zero
error
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
No comments:
Post a Comment