Sei sulla pagina 1di 6

Exceptions: Exceptions are such anomalous conditions (or typically an event) which changes the normal flow of execution

of a program. Exceptions are used for signaling erroneous (exceptional) conditions which occur during the run time processing. Occurrence of any kind of exception in java applications may result in an abrupt termination of the J ! or simply the J ! crashes which leaves the user unaware of the causes of such anomalous conditions. "owever Java provides mechanisms to handle such situations through its superb exception handling mechanism. #he Java programming language uses Exception classes to handle such erroneous conditions and exceptional events. Exception Hierarchy: #here are three types of Exceptions$
java.lang.Object | +--java.lang.Throwable | +--java.lang.Exception | | | +--java.lang.ClassNotFoundException | | | +--java.io. OException | | | | | +--java.io.FileNotFoundException | | | +--java.lang.!unti"eException | | | +--java.lang.Null#ointerException | | | +--java.lang. ndexOutO$%oundsException | | | +--java.lang.&rra' ndexOutO$%oundsException | +--java.lang.Error | +--java.lang.(irtual)achineError | +--java.lang.OutO$)e"or'Error

1. Checked Exceptions % #hese are the exceptions which occur during the compile time of the program. #he compiler checks at the compile time that whether the program contains handlers for checked exceptions or not. #hese exceptions do not extend &untimeException class and must be handled to avoid a compile%time error by the programmer. #hese exceptions extend the java.lang.Exception class 'or example if you call the readLine() method on a BufferedReader o !ect then the "#Exception may occur or if you want to build a program that could read a file with a specific name then you would be prompted to input a file name by the application. #hen it passes the name to the constructor for java.io.'ile&eader and opens the file. "owever if you do not pro$ide the name of any existin% file then the constructor thro&s !a$a.io.'ile(ot'oundException which abrupt the application to succeed. "ence this exception will be caught by a well%written application and will also prompt to correct the file name. list of checked exceptions (o)uch'ieldException *nstantiationException *llegal+ccessException ,lass(ot'oundException (o)uch!ethodException ,lone(ot)upportedException *nterruptedException ). *nchecked Exceptions -nchecked exceptions are the exceptions which occur during the runtime of the program. -nchecked exceptions are internal to the application and extend the java.lang.&untimeException that is inherited from java.lang.Exceptionclass. #hese exceptions cannot be anticipated and recovered like programming bugs. such as logic errors or improper use of an +/*. #hese type of exceptions are also called&untime exceptions that are usually caused by data errors. like arithmetic overflow. divide by 0ero 1ets take the same file name example as described earlier. *n that example the file name is passed to the constructor for 'ile&eader. "owever. the constructor will throw(ull/ointerException if a logic error causes a null to be passed to the constructor. "ere is the list of unchecked exceptions. *ndexOutOf2oundsException +rray*ndexOutOf2oundsException ,lass,astException +rithmeticException (ull/ointerException *llegal)tateException )ecurityException

+rithmetic Exception class Exc3 4 static void subroutine() 4 int d 5 67 int a 5 36 8 d7 9 public static void main()tring args:;) 4 Exc3.subroutine()7 9 9 #,Exception in thread <main< java.lang.+rithmeticException$ 8 by 0ero at #hrow=emo.subroutine(#hrow=emo.java$>) at #hrow=emo.main(#hrow=emo.java$?) .. Error #he errors in java are external to the application. #hese are the exceptional conditions that could not be usually anticipated by the application and also could not be recovered from. Error exceptions belong to Error and its subclasses are not subject to the catch or )pecify re@uirement. )uppose a file is successfully opened by an application for input but due to some system malfunction could not be able to read that file then the java.io.*OError would be thrown. #his error will cause the program to terminate but if an application wants then the error might be caught. /hro&in% Exceptions *f a method needs to be able to throw an exception. it has to declare the exception(s) thrown in the method signature. and then include a throw%statement in the method. Ex. class #hrow=emo 4 static void demoproc() 4 try 4 throw new (ull/ointerException(<demo<)7 9 catch((ull/ointerException e) 4 )ystem.out.println(<,aught inside demoproc.<)7 throw e7 88 re%throw the exception 9 9 public static void main()tring args:;) 4 try 4 demoproc()7 9 catch((ull/ointerException e) 4 )ystem.out.println(<&ecaught$ < A e)7 9 9 9

Catchin% Exceptions *f a method calls another method that throws checked exceptions. the calling method is forced to either pass the exception on. or catch it. ,atching the exception is done using a try% catch block. "ere is an example$ public void call=ivide() 4 try 4 int result 5 divide(B.3)7 )ystem.out.println(result)7 9 catch (2ad(umberException e) 4 88do something clever with the exception )ystem.out.println(e.get!essage())7 9 )ystem.out.println(<=ivision attempt done<)7 9 #he 2ad(umberException parameter e inside the catch%clause points to the exception thrown from the divide method. if an exception is thrown. *f no exeception is thrown by any of the methods called or statements executed inside the try%block. the catch%block is simply ignored. *t will not be executed. Chen the catch block is finished the program continues with any statements following the catch block. *n the example above the <)ystem.out.println(<=ivision attempt done<)7< statement will always get executed. -ropa%atin% Exceptions Dou donEt have to catch exceptions thrown from other methods. *f you cannot do anything about the exception where the method throwing it is called. you can just let the method propagate the exception up the call stack to the method that called this method. *f you do so the method calling the method that throws the exception must also declare to throw the exception. "ere is how the call=ivide() method would look in that case. public void call=ivide() throws 2ad(umberException4 int result 5 divide(B.3)7 )ystem.out.println(result)7 9 #he exception is propagated to the method that calls call=ivide. /rogram execution doesnEt resume until a catch%block somewhere in the call stack catches the exception. +ll methods in the call stack between the method throwing the exception and the method catching it have their execution stopped at the point in the code where the exception is thrown or propagated.

Example: Catchin% "#Exception0s *f an exception is thrown during a se@uence of statements inside a try%catch block. the se@uence of statements is interrupted and the flow of control will skip directly to the catch%block. #his code can be interrupted by exceptions in several places$ public void open'ile() 4 try 4 88 constructor may throw 'ile(ot'oundException 'ile&eader reader 5 new 'ile&eader(<some'ile<)7 int i567 while(i F5 %3) 4 88reader.read() may throw *OException i 5 reader.read()7 )ystem.out.println((char) i )7 9 reader.close()7 )ystem.out.println(<%%% 'ile End %%%<)7 9 catch ('ile(ot'oundException e) 4 88do something clever with the exception 9 catch (*OException e) 4 88do something clever with the exception 9 9 Example$ /ropagating *OExceptionEs #his code is a version of the previous method that throws the exceptions instead of catching them$ public void open'ile() throws *OException 4 'ile&eader reader 5 new 'ile&eader(<some'ile<)7 int i567 while(i F5 %3) 4 i 5 reader.read()7 )ystem.out.println((char) i )7 9 reader.close()7 )ystem.out.println(<%%% 'ile End %%%<)7 9 *f an exception is thrown from the reader.read() method then program execution is halted. and the exception is passed up the call stack to the method that called open'ile(). *f the calling method has a try%catch block. the exception will be caught there. *f the calling method also just throws the method on. the calling method is also interrupted at the open'ile() method call. and the exception passed on up the call stack. #he exception is propagated up the call stack like this until some method catches the exception. or the Java irtual !achine does.

'inally Dou can attach a finally%clause to a try%catch block. #he code inside the finally clause will always be executed. even if an exception is thrown from within the try or catch block. *f your code has a return statement inside the try or catch block. the code inside the finally%block will get executed before returning from the method. "ere is how a finally clause looks$ public static 'ile*nput)tream fB()tring file(ame) 4 'ile*nput)tream fis 5 null7 try 4 fis 5 new 'ile*nput)tream(file(ame)7 9 catch ('ile(ot'oundException ex) 4 )ystem.out.println(<fB$ Oops. 'ile(ot'oundException caught<)7 return fis7 9 finally 4 )ystem.out.println(<fB$ finally block<)7 return fis7 9 88 ,ompiler error$ statement not reacheable 88 )ystem.out.println(<fB$ &eturning from fB<)7 88 return fis7 9

Potrebbero piacerti anche