Java uses the keyword tryto preface a block of code that is likely to cause an error
condition and “throws” an exception.
A catch block defined by the keyword catch “catches” the exception “thrown”
by the try block and handles it appropriately.
The catch block is added immediately after the try
block as shown below:
……..
……..
try
{
Statement; //Generate an exception
}
catch (Exception-type e)
catch (Exception-type e)
{
Statement; //processes the exception
}
………
………
The try
block can have one or more statements that could generate an exception. If any
statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch
block that is placed next to the try block.
Every try
statement must be followed by at least one catch statement.
The catch
statement is passed a single parameter, which is reference to the exception
object thrown by the try block. If the catch parameter matches with the type of
exception object, then the exception is caught and statements in the catch
block will be executed. Otherwise, the exception is not caught and the default
exception handler will cause the execution to terminate.
Example:
class Error
{
public static void
main(String args[])
{
int a=10,b=10,c=20,d;
try
{
d=c/(a-b);
}
catch(ArithmeticExceptione)
{
System.out.println("Arithmetic
exception occurred");
}
d=a+b;
System.out.println("D
= "+d);
}
}
Output:
Arithmetic exception
occurred
D = 20
Using Finally
Statement:
o Java supports finally
statement that can be used to handle an exception that is not caught by any of
the previous catch statements.
o finallyblock can be used to handle any exception generated
within the try block.
o It may be added immediately after the try block or
after the last catch block as shown below:
try
try{
{
……
…..
}
….. catch(…) {
}
…….
finally
}
{
……..
…..finally {
…..
……
}
}
o When a finally block is defined, this is guaranteed
to execute, regardless of whether or not any exception is thrown.
o Example:
class
Finally
{
public
static void main(String args[])
{
int
a=10,b=10,c=20,d;
try
{
d=c/(a-b);
}
catch(ArithmeticException
e)
{
System.out.println("Arithmetic
exception occurred");
}
finally
{
System.out.println("Finally
is executed");
}
d=a+b;
System.out.println("D
= "+d);
}
}
Output:
Arithmetic
Exception Occurred
Finally
is executed
D
= 20
No comments:
Write comments