Home
| | Sitemap
||Page number :19
Basic Exception Handling in Java
Java provides us an excellent exception management system, hence we can protect our programs from any run time errors. This robustness is achieved through keywords like “try, catch, throw and throws”. The contents of this chapter are out of course if you compare them with the ICSE syllabus, but a basic knowledge will really help you in understanding the forthcoming chapters.
Exception
Exception is some unusual condition that sometimes generates during the execution of our code. The reason may be an invalid input, no input and even violation of some security features. If we don’t handle the exception ourselves then the Java Run Time automatically handles and reports the exception, finally terminating the program. This can be embarrassing if you are writing a professional program (Take your own project as an example). Thus handling some exceptional condition is really important.
Using try and catch The two keywords “try and catch” are extremely useful for handling run time exception. If we suspect a part of code to be prone to exceptions, we can enclose it within the try block. If an exception occurs, it is handled by the catch block as directed earlier by us. We can even manually throw an exception using “throw and throws” keyword. Syntax—
try
{
// Statements // Code } catch( ExcepionType obj) { //Catch block that handles exception // Any suitable actions that are needed to be taken } Look at this program that will generate an error. Here we have not used try catch to protect our code from exceptions.
class airtexc2 { public static void main(String args[]) { int no,no2,ans; no=10; no2=0; ans=no/no2; System.out.println("Exception Occurred"); } }
Output—
Line no 8: ans=no/no2; caused a divide by zero exception error that resulted in an abnormal termination of the program. The line “System.out.println("Exception Occurred");” was not executed.
Now the same program is written using try and catch to handle exception.
class airtexc { public static void main(String args[]) { int no,no2,ans; no=10; no2=0; try { System.out.println("Try block begins"); ans=no/no2; } catch(ArithmeticException e) { System.out.println(" Sorry!!An Exception occured"); System.out.println(" Exception Details"+e); } System.out.println("EXCEPTION DETAIL PRINTED"); } }
Output----

page 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29