Presentation is loading. Please wait.

Presentation is loading. Please wait.

Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.

Similar presentations


Presentation on theme: "Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined."— Presentation transcript:

1

2 Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined Exceptions

3 Introduction “ An exception is a condition that cannot be resolved within the context of the operation that caused it. ” To throw an exception is to signal that such a condition has occurred. To catch an exception is to transfer control to an exception handling routine, altering the normal execution flow of the program. Because exceptions are outside the normal operation of a program the normal, default action is to write out an error message and terminate the offending process.

4 Questions What is an Error? What is the Difference between Error and Exception?

5 Answers Error: “ An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. “ Errors can not be caught. Examples: Stackoverflow and underflow

6 Answers Exception: “The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. “ Exception can be caught using key words such as try and catch block.

7 Exceptions Exceptions can occur at many levels: Hardware/operating system level Arithmetic exceptions; divide by 0, under/overflow. Memory access violations; stack over/underflow. Language level Type conversion; illegal values, improper casts. Bounds violations; illegal array indices. Bad references; null pointers. Program level User defined exceptions.

8 Exception Example public class UnhandledException { public static void main(String[] args) { int num1 =0,num2 =5; int num3 = num2/num1; System.out.println(" Value = " +num3); }

9 Exception Hierarchy

10 Classification of Exceptions Exceptions can be classified as NullPointerException ArrayIndexOutOfBoundsExc eption IOException These exceptions are define by Java and they reside in java.lang package. Built-in Exceptions Exceptions defined by users. User-Defined Exceptions Examples of Exception:

11 Built-in Exceptions Built-in Exceptions in Java Checked Exception: The invalid conditions that occur in java program due to invalid user input, database problems etc. Examples: IOException SQLException Unchecked Exception: They are run time errors that occur because of programming errors such as invalid arguments passed to a public method. Examples: ArrayIndexOutOfBoundsException NullPointerException

12 Checked Exception Exception NameDescription ClassNotFoundExceptionClass not found InstantiationException Attempt to create an object of an abstract class or interface. IllegealAccessExceptionAccess to a class is denied. NoSuchMethodExceptionA requested method does not exist. NoSuchFieldExceptionA requested field does not exist. InterruptedException One thread has been interrupted by another thread. CloneNotSupportedException Attempt to clone an object that does not implement Cloneable interface.

13 Unchecked Exception Exception NameDescription ArithmeticException Arithmetic error, such as divide by zero. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. IllegealArgumentException Illegeal argument used to invoke a method. ClassCastExceptionInvalid class cast ArithmeticException Arithmetic error, such as divide by zero. NegativeArraySizeExceptionArray created with a negative size.

14 Handling exceptions – General Example Snippet of a pseudocode follows: ………… IF B IS ZERO GO TO ERROR C=A/B PRINT C GO TO EXIT ERROR: DISPLAY “DIVISION BY ZERO” EXIT: END Block that handles error Block that handles error

15 Exception Handling in Java Try CatchThrow ThrowsFinally Exceptions in Java can be handled by five keywords

16 Exception Handling in Java – Contd., used with the code that might throw an exception. TRY This statement is used to specify the exception to catch and the code to execute if the specified exception is thrown. CATCH is used to define a block of code that we always want to execute, regardless of whether an exception was caught or not. FINALLY Typically used for throwing user-defined exceptions THROW Lists the types of exceptions a method can throw, so that the callers of the method can guard themselves against the exception THROWS Exception

17 Exception Handling Mechanism The basic concepts of exception handling are throwing an exception and catching it. Statement that causes an exception Statement that causes an exception Try Block Statement that handles the exception Statement that handles the exception catch Block Throws exception object Exception object creator Exception Handler

18 Exception Handling syntax try { statements } catch (Exception class object) { statements } finally { //Close file handles //Free the resources }

19 Try and catch public class TryCatchDemo{ public static void main(String [] args){ int x,y; try{ x = 0; y = 10/x; System.out.println(“Now What ???”); } catch(ArithmeticException e){ System.out.println(“Division by zero”); } System.out.println(“Hi I am back !!!”); } TryCatchDemo

20 Using multiple Catch Statements try catch(exception-class1 object) { //blocks of code } catch(exception-class1 object){ //blocks of code } A single try block can have many catch blocks. Multiple catch statements are used when a try block has statements that raise different types of exceptions. MultipleCatchBlockDemo

21 Handling the Unreachable Code Problem If in an program the first catch block contains the Exception class object then subsequent catch blocks are never used. The excetion class being the super class, java gives a compiler error stating that the subsequent catch blocks have not been reached. This phenomenon is termed as “unreachable code problem”. UnreachableCodeDemo

22 Finally Block Ensures that all cleanup work is taken care of when an exception occurs Used in conjunction with a try block Guaranteed to run whether or not an exception occurs Syntax finally { // Blocks of code} finally catch block finally Exception No exception try block Finally Demo

23 Rules for Try-Catch-Finally For each try block there can be one or more catch block but only one finally block. A finally block cannot execute without a try block. Try block can be nested with catch blocks.

24 Throw and Throws Keyword "throws" declares that your method is capable of throwing an exception. "throw" actually does the work, of throwing the exception. Example : public void doSomething() throws ApplicationException { try{ } catch(Exception e){ // catch all excpetions here throw ApplicationException("An error occurred while trying connect to DB"); } } ThrowsAndThrowKeyWordDemo

25 User Defined Exceptions “ UserDefined Exceptions are any subcalss of Exception which is defined by a user to define their own exceptional condition. “ Any violation of Business rules of an application can be handled using User Defined Exception.

26 User Defined Exceptions – Contd., For example, If the person is in the business of selling motorcycles and need to validate an order which has been placed by a customer, creating a user- defined exception in the Java programming language can be done by a creating a new class which can be named TooManyBikesException. if someone tries to place an order for more motorcycles than you can ship, you can simply throw a user-defined exception.

27 User Defined Exception – Contd., Rules for writing UserDefinedException Class: a.Userdefined Exception class has to exend an Exception class. b.When an business rule is violated, a userdefined exception object has to be created and thrown using throw key word. c.Any userdefined Exception thrown using the throw key word has to be handled in respective catch block of userdefined Exception.

28 User Defined Exception – Contd., Class UserDefinedException extends Exception { String getMessage() { Return “logical message related to error raised”; } Example: UserDefinedExceptionDemo

29 Summary An exception is a run time error that can be defined as an abnormal event that occurs during the execution of a program and disrupts the normal flow of instructions. In Java, the Throwable class is the superclass of all the exception classes. The Exception class and the Error class are two direct subclasses of the Throwable class. The built-in exceptions in Java are divided into two types on the basis of the conditions where the exception is raised: – Checked Exceptions or Compiler-enforced Exceptions – Unchecked exceptions or Runtime Exceptions

30 Summary – Contd., You can implement exception handling in your program by using the following keywords: – try – catch – throw – throws – Finally You use multiple catch blocks to throw more than one type of exception.

31 Summary – Contd., The finally clause is used to execute the statements that need to be executed whether or not an exception has been thrown. The throw statement causes termination of the normal flow of control of the Java code and stops the execution of subsequent statements after the throw statement. The throws clause is used by a method to specify the types of exceptions the method throws. You can create your own exception classes to handle the situations specific to an application

32 References http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html http://www.javabeginner.com/java-exception-handling.htm http://mindprod.com/jgloss/exception.html http://www.tutorialhero.com/tutorial-71-java_exceptions.php


Download ppt "Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined."

Similar presentations


Ads by Google