Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exception Handling.

Similar presentations


Presentation on theme: "Exception Handling."— Presentation transcript:

1 Exception Handling

2 Objectives What is an error condition?
Error Handling in Conventional Languages Exceptions Exception Handling in Java Exception Hierarchy Throwable Class Error and Exception Types of Exceptions Throwing Exceptions Declaring Exceptions per Method Catching Exception Designing user-defined Exception classes Method Overriding and Exceptions

3 Error Condition An error is a condition due to which a program cannot continue normal execution and needs to be abruptly terminated Some of the examples of error condition are Program run out of memory Files are lost, corrupted Network connections are dropped Database is not available There is no way these conditions can be predicted and we cant prevent them from happening. Refer to: DivisionErroDemo.java

4 Error Conditions Our applications should be built to survive ‘error conditions’ The program must handle the error situation, probably giving the user opportunity to correct the situation, close the resources and exit gracefully

5 Error Handling in traditional languages
Traditional error handling methods include Boolean functions (which return TRUE/FALSE). Integer functions (returns –1 on error). And other return arguments and special values. int main () { int res; if (can_fail () == -1) { cout << "Something failed!" << endl; return 1; } if(div(10,0,res) == -1) { cout << "Division by Zero!" << endl; return 2; return 0;

6 Problems with traditional approach
Functions can not return the details of the error condition Caller is not forced to receive the value returned by the function Multiple if-else leads to cluttered code and is difficult to maintain

7 Exception Handling in Java
Java’s support for error handling is done through Exceptions. What is an exception? An exception can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions In the wake of such an event, the JVM creates an exception object, that contains information about the error, including its type and state of the program when the error occurred. Creating an exception object and notifying the caller of the method is called throwing an exception. Java allows programmers to define their own means of handling exceptions when they occur.

8 Exception Handling Mechanism
Introduction to JAVA Exception Handling Mechanism Thrown exception matched against first set of Exception handlers. Exception thrown here If it fails to match it is matched against the next set of Exception handlers & so on. Exception Handler Exception Handler If the exception matches none of the exception handlers,the program is Abandoned.

9 Why use Exceptions? Exception handling provides the programmer with many advantages over traditional error-handling techniques: Exceptions cannot be ignored, they must be caught or the application will terminate. It provides a means to separate error-handling code from program code. It provides a mechanism for propagating errors up the method call stack, meaning that methods higher up the call chain can be allowed to handle problems originating lower in the chain. It provides a way to organize and differentiate between different types of abnormal conditions. Both, application logic and problem handling logic, become simpler, cleaner and clearer.

10 Java Exception Hierarchy
Throwable Error Exception RuntimeException (Unchecked Exceptions) (Checked Exceptions) Virtual Machine Error Object

11 Errors Errors are exception conditions that are external to the application. For eg OutOfMemoryError StackOverflowError Errors are not handled by the application

12 Types of Exceptions Exceptions are of two types Checked Exceptions
Unchecked Exceptions

13 Classifying Java Exceptions
Introduction to JAVA Classifying Java Exceptions Unchecked Exceptions It is not required that these types of exceptions be caught or declared on a method. Runtime exceptions can be generated by methods or by the JVM itself. The subclasses of RuntimeException class are considered as unchecked exceptions Errors are generated from deep within the JVM, and often indicate a truly fatal state. Checked Exceptions Must either be caught by a method or declared in its signature. Compiler forces them to be handled Must be handled when they occur. Are the direct subclasses of Exception class Refer to: UncheckExceptionDemo.java CheckExceptionDemo.java

14 Implementing Exception Handling
Introduction to JAVA Implementing Exception Handling try catch finally throw throws

15 Implementing Exception Handling
Introduction to JAVA Implementing Exception Handling Using try and catch statements The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run time error.

16 Implementing Exception Handling
Introduction to JAVA Implementing Exception Handling try { // Statements that cause an exception. } catch(ExceptionName obj) // Error handling code. Refer to: DivisionErrorHandledDemo.java

17 Using Multiple catch blocks
Introduction to JAVA Using Multiple catch blocks A single try block can have many catch blocks. The multiple catch blocks generate unreachable code error. If the first catch block contains the Exception class object then the subsequent catch blocks are never executed. If this happen it is known as unreachable code problem. To avoid unreachable code error, the last catch block in multiple catch blocks must contain the Exception class object. Refer to: MultiCatchDemo.java

18 Using Multiple catch blocks
Introduction to JAVA Using Multiple catch blocks Order Matters! Less general first! try { // dangerous code here! } catch(ArithmeticException e) { // Specific error handling here catch(RuntimeException e) { // More general error handling here Refer to: MultiCatchDemo1.java Note that one catch is more general than the other. Also note that the more specific one here will override the more general one THE ORDER MATTERS HERE!

19 Syntax of finally block
Using finally clause The finally block is used to process certain statements, no matter whether an exception is raised or not. The finally block is generally used to write the clean as the finally block will always get executed. One try block can have only one finally block attached. try{ // Block of code } finally { // Block of code that is always executed irrespective of an exception being raised or not. Syntax of finally block

20 Using try/catch/finally
// … } catch (ExceptionType1 identifier) { } catch (ExceptionType2 identifier) { } finally { } Refer to: ExceptionDemoFinally.java WithFinally.java

21 Introduction to JAVA Throwing an Exception The throw statement causes termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown when the throw statement is executed. The throw clause transfers the control to the nearest catch block handling the type of exception object throws. The following syntax shows how to declare the throw statement: throw ThrowableObj Refer to: ThrowDivisionErroDemo.java

22 Exception Propagation
Manage exceptions by collecting them in a specific method to propagate the exceptions to calling method To prevent scattering of exception handling Exception Propagation Order If there is no catch block to deal with the exception, it is propagated to calling method All executions are ignored until finding the exception handler Refer to: ExceptionPropagation.java

23 Propagation of Uncaught Exception

24 Using throws Statement
Introduction to JAVA Using throws Statement The throws statement is used by a method to specify the types of exceptions the method throws. If a method is capable of raising an exception that it does not handle, the method must specify that the exception has to be handled by the calling method. This is done using the throws statement. Refer to: ThrowsDemo.java

25 Method overriding and Exceptions
The checked exception classes named in the throws clause are part of the contract between the implementer and user of the method or constructor. The throws clause of overriding method can specify all or none of the exception classes specified in the throws clause of the overridden method in the super class. The overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted. However the overriding method can throw exceptions which are subclasses of the exceptions in the throws clause of the overridden method.

26 Rethrowing Exceptions
Example try { // Code that originates an arithmetic exception } catch(ArithmeticException e) { // Deal with the exception here throw e; // Rethrow the exception to the calling program } Refer to : Rethrowing.java

27 User Defined Exceptions
Introduction to JAVA User Defined Exceptions Defining your own exceptions let you handle specific exceptions that are tailor-made for your application. Steps to Create a User Defined Exception Create a class that extend from a right kind of class from the Exception Hierarchy. Create the exception object based on some condition and throw it explicitly Refer to: UserDefinedExceptionsDemo.java

28 Best practices There are certain best practices which must be followed while doing exception Handling A detailed list of these best practices with their explanation can be found at:


Download ppt "Exception Handling."

Similar presentations


Ads by Google