Excepton Handling
While
writing a program we will get two types of errors
1.
Compile time errors(due to wrong syntax,semantics)
2.
Runtime errors(due to wrong input/outputs,wrong logics )
ü Exception
is a RUNTIME ERROR occurred during the program execution
ü If
any problem raised at the time of runnig the program is called RUNTIME ERROR.
ü But
in c/c++ if any RUNTIME ERROR occurs it terminates abruptly and the process is
killed.
ü This
problem is resolved in JAVA with EXCEPTION HANDLING MECHANISM.
ü When
any EXCEPTION is raised it is handled by JVM default handler and using
TRY,CATCH,FINALLY Blocks.
Ex:--
/*
-
the process of raising exception in one class
-
and the abnormal termination becoz we are not providing any command line args.
*/
class AbnormalTermination{
public static void main(String[] args) {
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=(a/b);
System.out.println("The value of
c:"+c);
}//main()
}//class
To
handle the exception we will use TRY,CATCH,FINALLY blocks
class
Exh2 {
public static void main(String[] args) {
int a[]=new int[5];
try{
System.out.println(a[3]);
System.out.println(a[4]);
System.out.println(a[6]);
}
catch
(ArrayIndexOutOfBoundsException ai){
System.out.println(ai);
}
finally{
System.out.println(“finally
called”);
} } }
Observations:--
1.
The try block consists of Exception raising statements.when an exception is
raised it identifies the type of the exception and creates an object for the
specified exception class .
2.
and It throws the object to catch block .
3.
Then catch block handles that Exception and consists of Exception class object.
4.
It is used to store the Exception reference object and will do some
appropriate action.
5.
The finally block:--If any error occurred or not but the finally block
statements are executed.
6.
This finally block is mainly used to perform mandatory statements.
/*
-
The proccess of handling Exceptions using try with multiple catch blocks.
-
call this program as ExceptionHandling.java
*/
class
ExceptionHandling{
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 value of
C:"+c);
}
catch(ArrayIndexOutOfBoundsException aie){
System.out.println("Should
pass atleast two arguments ");
}
//System.out.println("After aie catch
block");//Compilation Error
catch(ArithmeticException ae){
System.out.println("Should not pass second argument as zero");
} catch(NumberFormatException nfe){
System.out.println("Should pass two
arguments as integers only");
} catch(Exception
e){
e.printStackTrace ();//It
prints all the details about Exceptions
}
System.out.println("After all catch
block, I am not related to any exceptional condition, so
I
can be executed");
}//main()
}//class
Note:--
1.
If no of Exceptions we give it takes only first exception not all.
2.
Exception is the super class for exception handling, if first it we give then
it executes only super class exception so always this we use at last.
3.
And if we don’t know which Exception is rising we can use super class Exception
then automatically it takes care of all exceptions.
4.
If we give no of Exceptions in a
program, then if none of the one is not matching then it Executes superclass
Exception.
The
diagram below illustrates Java Exception class hierarchy.
Darker
colored are checked exceptions. Any checked exceptions that may be thrown in a
method must either be caught or declared in the method’s throws clause. Checked
exceptions caught at compile time. The
lighter colored classes are unchecked exceptions ,those are not checked by the
compiler at compilation time. Unchecked:--This we don’t know till run time.
Checked:--This we know at compile time itself.
INNER-TRY-CATCH-BLOCK
Perticularly if we suspect any error in a
specific line we use this.
Ex:
class
InnerTry{
public static void
main(String [] args) {
int
a[]=new int[3];
try{
System.out.println(a[2]);
try{
System.out.println(a[3]);
}
catch(ArrayIndexOutOfBoundsException
ae) {
//ae.printStackTrace();
}
}
catch(Exception
e){
System.out.println(e);
}
}
}
Differences:
1)
These are the exceptions which occur during the compile time of the program whereas
unchecked exceptions are the exceptions which occur during the run time of the
program.
2)
Checked exceptions must be explicitly caught or propagated as described in
Basic try-catch-finally Exception Handling. Unchecked exceptions do not have
this requirement. They don't have to be caught or declared thrown.
3)
We need to report to the JVM by use try, catch or Throws keyword in Exceptions.
The
process of throwing exceptions explicitly using throw keyword.
class
ThrowDemo {
public static void main(String[] args) {
int a=20;
if (args.length<1){
System.out.println("using
throw");
throw new
ArrayIndexOutOfBoundsException(args.length);
}
int
b=Integer.parseInt(args[0]);
System.out.println(b);
if (b==0){
System.out.println("Exception
thrown ");
throw new
ArithmeticException("/ by zero");
}
int c=(a%b);
if (c==0){
System.out.println(c);
System.out.println("Exception
thrown by JVM");
int x=10/c;
}
} }
Throws
1.
By using “ throws ” keyword we can throw Exception class object.
2.
By using throws keyword we can throw any no of exceptional classes objects at a
time.
3.
No need of using any try, catch also.
class
ThrowsEx {
public
static void main(String [] args) throws ArithmeticException,ArrayIndexOutOfBoundsException,Exception
{
//if
we use throws keyword no need of try n catch
int a[] = new int[3];
System.out.println(10/10);
System.out.println(a[20]);
div(2,0);//static
method no reference is needed.
}
static
void div(int x,int y)throws ArithmeticException{
System.out.println("the
division is:"+(x/y));
} }
We
Can use combination of throws and try-catch.
class
ThrowsEx1 {
public static void
main(String [] args) throws
ArithmeticException,ArrayIndexOutOfBoundsException,Exception {
int a[] = new int[3];
System.out.println(10/10);
try{
System.out.println(a[20]);
}
catch
(ArrayIndexOutOfBoundsException aio) {
System.out.println(aio);
System.out.println("am
in catch");
}
div(2,0);//static
method no reference is needed.
}
static
void div(int x,int y)throws ArithmeticException{
System.out.println("the
division is:"+(x/y));
} }
User-defined-Exceptions
1.
We can also create User-defined-Exceptions by extending our class from
Exceptions class.
public
class NegativeAge extends Exception{
public NegativeAge() {
System.out.println("Entered
age in negative format");
}
public String toString(){
return "do not enter
negative values";
} }
Then
this user-defined Exception will be stored in Exceptions super class.we can use this in any Exceptions
program like pre-defined Exceptions.Implementing user-defined Exception
class
userExh{
public static void main(String[] args) {
int age=-20;
try{
if(age<0){
throw new NegativeAge();
}
}
catch (NegativeAge na){
System.out.println(na);
}
} }
#
printStackTrace() method will print
$ exception type
$ reason for that exception and
$ place of that exception in the program.
#
getMesssage() method will print only
$ reason for that exception.
No comments:
Post a Comment