130 likes | 329 Views
CS1054: Lecture 22. - Exception Handling. Java Exception. Describes an exceptional condition that has occurred in a piece of code. An object representing that exception is created and thrown in the method that caused the exception. At some point the exception has to be caught and processed
E N D
CS1054: Lecture 22 - Exception Handling
Java Exception • Describes an exceptional condition that has occurred in a piece of code. • An object representing that exception is created and thrown in the method that caused the exception. • At some point the exception has to be caught and processed • They report to the calling method some error condition.
Keywords • try • catch • throw • throws • finally
Default Handler • Exc1 and Exc2
Using try and catch • Default handler helps, still you may want to handle exceptions yourself. • This also prevents program for terminating automatically. • For this we use try and catch block. • Exc3
Import points – try and catch • Once exception is thrown program control transfers from try to catch block. • Execution never returns from catch to try block • After catch, program continues with the next line in the program following entire try/catch block.
Multiple catch blocks • More than one type of exceptions can be thrown by a single piece of code. • To handle this, you can specify more than one catch clauses. • Each catch statement is inspected, and the first one whose type matches the exception is executed.
Important • When using Exceptions: • Subclasses should be written always before superclass.
Throw • Allows your program to explicitly throw an exception.
Throws • If a method is capable of causing an exception that it doesn’t handle, it must specify this behavior. • A throws clause lists different types of exceptions that a method might throw.
finally try { } finally { }
Catch vs. Finally • A try statement requires either finally or catch. • Statements in catch block get executed only if an exception is thrown. • Statements in finally block always get executed.
Exception – Handling blocks try { // block of code to monitor of errors } catch (ExceptionType1 exOb) { // exception handler for Exception Type 1 } catch (ExceptionType1 exOb) { // exception handler for Exception Type 2 } finally { // block of code to be executed before try block ends }