recovery procedures from error conditions present in a software application.
• Exception Handling is an abnormal condition
that arises in a code sequence at run time. In other words, an exception is a run-time error. Error Handling VS Exception Handling
• Exceptions are those which can be handled at
the run time, whereas errors cannot be
handled at the run time.
Exception Handling • In Java it is handled using 4 keywords Try Catch Throws Finally Using Keywords
• try – A block of source code that is to be
monitored for exception • catch – It handles the specific type of exception along with the try block. • throws – It specifies the exception that can be thrown by a particular method. • finally – it specifies the code that must be executed even though exception may or may not be occur. Handling try-catch block Finally Block Handling try-catch block( Cont..) • The statement(s) that are likely to cause an exception are enclosed within a try block. • For these statements the exception is thrown. • There is another block defined by the keyword catch which is responsible for handling the exception thrown by the try block. • As soon as exception occurs it is handled by the catch block. • The catch block is added immediately after the try block. Hierarchy of Exception classes Syntax of try- catch try { //exception gets generated here } Catch(Type_of_Exception) { //exception is handled here } throws Syntax
type method-name() throws exception-list { // body of method } Example (Unit Level) Finally Block Example