♠ Posted by Unknown in Core Java at 01:36
Exception handling Examples
When Runtime Error occurred in
program can be terminated abnormally and cannot display output or proper error
message.
So, at runtime if program can be
terminated without inform any error that can be understand by programmer, it is
very crucial to find an error in program or taken output.
If programmer can be expected that
error in his code it can be handled by the java exception handling method.
Java will help the programmer to
handle exception using following five keywords : try, catch, throw, throws, and
finally.
Syntax :
try.....catch :
try
{
Exception
expected
code
segment;
}
catch(exception object)
{
when
exception occurred
code
segment;
}
try with multiple catch block
try
{
Exception
expected
code
segment;
}
catch(exception object)
{
when
exception occurred
code
segment;
}
catch(exception object)
{
when
exception occurred
code
segment;
}
try with multiple catch and finally
try
{
Exception
expected
code
segment;
}
catch(exception object)
{
when
exception occurred
code
segment;
}
catch(exception object)
{
when
exception occurred
code
segment;
}
finally
{
Code
Segment that must be executed
either
exception is raised or not.
}
finally blocked must be written last
in the try...catch block.
Example :
import java.lang.*;
import java.io.*;
class
TryExample1
{
public
static void main(String[] args)
{
int
a, b, c;
try
{
a
= Integer.parseInt(args[0]);
b
= Integer.parseInt(args[1]);
c
= a + b;
System.out.println("The
Sum is : " + c);
}
catch(ArrayIndexOutOfBoundsException
e)
{
System.out.println("You
cannot use args[] in proper way...");
}
catch(NumberFormatException
e)
{
System.out.println("You
cannot Enter Numeric values for Variables....");
}
finally
{
System.out.println("This
Block Expected Any Time....");
}
}
}
0 comments:
Post a Comment