|
What is an Exception
Handling?
Exception Handling
What is an Exception ?
Let us see what happens when an exception occurs
and is not handled properly
When you compile and run the following program
public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// a division
by 0 occurs here.
int z = x/y;
System.out.println("after
didvision");
}
}
the execution of the Test stops and this is caused
by the division by zero at - x/y - an exception has been thrown but has
not been handled properly.
How to handle an Exception ?
To handle an Exception, enclose the code that
is likely to throw an exception in a try block and follow it immediately
by a catch clause as follows
public class Test{
public static void main(String str[]){
int y = 0;
int x = 1;
// try block to
"SEE" if an exception occurs
try{
int z = x/y;
System.out.println("after didvision");
// catch clause below handles the
// ArithmeticException generated by
// the division by zero.
} catch
(ArithmeticException ae)
{System.out.println(" attempt to divide
by 0");}
System.out.println("
after catch ");
}
}
The output of the above program is as follows
attempt to divide by 0
after catch
the statement - System.out.println("after didvision")
- is NOT executed, once an exception is thrown, the program control moves
out of the try block into the catch block.
More Java Questions
Have a Java Problems
Do you have
a Java Question?
Java Books
Java Certification, Programming,
JavaBean and Object Oriented Reference Books
Best Regards,
Java Programming Hints and Tips
All the site contents are Copyright © www.sap-img.com
and the content authors. All rights reserved.
All product names are trademarks of their respective
companies.
The site www.sap-img.com is not affiliated with or endorsed
by any company listed at this site.
Every effort is made to ensure the content integrity.
Information used on this site is at your own risk.
The content on this site may not be reproduced
or redistributed without the express written permission of
www.sap-img.com or the content authors.
|