Presentation is loading. Please wait.

Presentation is loading. Please wait.

Exceptions Handling Prepared by: Ligemm Mae del Castillo.

Similar presentations


Presentation on theme: "Exceptions Handling Prepared by: Ligemm Mae del Castillo."— Presentation transcript:

1 Exceptions Handling Prepared by: Ligemm Mae del Castillo

2 Objectives After completing this lesson, you should be able to: 1. Handle exceptions by using try, catch and finally 2. Differentiate between the use of throw and throws 3. Use existing exception classes 4. Differentiate between checked and unchecked exceptions 5. Define your own exception classes 6. Explain the benefits of using assertions 7. Use assertions

3 What are Exceptions? Errors that cause that disrupt program execution. Makes programs terminate abnormally if not handled. Some examples are divide by zero errors, accessing the elements of an array beyond its range, invalid input, hard disk crash, opening a non-existent file and heap memory exhausted.

4 The Error and Exception Classes Object Throwable ExceptionError Error vs. Exception

5 Exception Class Exception ClassNotFoundException CloneNotSupportedException IOException AWTException RuntimeException Several more classes

6 Error Class Error LinkageError VirtualMachineError AWTError Several More Classes

7 Runtime Exception ArithmeticException NullPointerException IndexOutOfBoundsException IllegalArgumentException

8 Error Class vs. Exception Class The Exception class is refer to conditions that user programs can reasonably deal with. These are usually the result of some flaws in the user program code. Example of Exceptions are the division by zero error and the array out-of-bounds error. The Error class, on the other hand, is used by the Java run-time system to handle errors occurring in the run- time environment. These are generally beyond the control of user programs since these are caused by the run-time environment. Examples include out of memory errors and hard disk crash.

9 Checked and Unchecked Exception RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with them.

10 CloneNotSupportedException Possible Reason For Exception Attempt to clone an object whose defining class does not implement the Cloneable interface.

11 ClassNotFoundException Possible Reason For Exception Attempt to use a class that does not exist. This exception would occur, for example, if you tried to run a nonexistent class using the java command, or if your program were composed of, say, three files, only two of which could be found.

12 IOException Possible Reason For Exception Related to input/output operations, such as invalid input, reading past the end of a file, and opening a nonexistent file. Examples of subclasses of IOException are InterrutedIOException, EOFException(EOF is short for Enf Of File), and FileNotFoundException.

13 AWTException Possible Reason For Exception Exception in GUI components.

14 ArithmeticException Possible Reason For Exception Dividing an integer by zero. Note that floating-point arithmetic does not throw exceptions.

15 NullPointerException Possible Reason For Exception Attempt to access an object through null reference variable.

16 IndexOutOfBoundsException Possible Reason For Exception Index to an array is out of range. IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are logic errors that should be corrected in the program.

17 IllegalArgumentException Possible Reason For Exception A method is passed an argument that is illegal or inappropriate.

18 Note: –In general, each exception class in Java API has at least two constructors: a no-argument constructor, and a constructor with a String argument that describes the exception. This argument is called the exception message, which can be obtained using getMessage().

19 Understanding Exception Handling Java’s exception-handling model is based on three operations: –Declaring an exception –Throwing an exception –Catching an exception

20 Catching Exceptions try, catch and finally are used to handle different types of exceptions. Given below is the general syntax for writing a try-catch statement. try { } catch ( ) { }

21 Catching Exceptions Coding Guidelines: The catch block starts after the close curly brace of the preceding try or catch block. Statements within the block are indented.

22 Catching Exceptions A particular code monitored in the try block may cause more than one type of exception to occur. In this case, the different types of errors can be handled using several catch blocks. Note that the code in the try block may only throw one exception at a time but may cause different types of exceptions to occur at different times.

23 code that handles more than one type of exception. class MultipleCatch { public static void main(String args[]) { try { int den = Integer.parseInt(args[0]); //line 4 System.out.println(3/den); //line 5 } catch (ArithmeticException exc) { System.out.println(“Divisor was 0.”); } catch (ArrayIndexOutOfBoundsException exc2) { System.out.println(“Missing argument.”); } System.out.println(“After exception.”); }

24 Nested trys are also allowed in Java. class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args[0]); try { int b = Integer.parseInt(args[1]); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Divide by zero error!"); } } catch (ArrayIndexOutOfBoundsException exc) { System.out.println(“2 parameters are required!"); }

25 Finally Keyword try { } catch ( ) { }... } finally { } Coding Guidelines: Again, same coding convention applies to the finally block as in the catch block. It starts after the close curly brace of the preceding catch block. Statements within this block are also indented.

26 Finally Keyword The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught.

27 Four different scenarios are possible in a try-catch-finally block 1.a forced exit occurs when the program control is forced to skip out of the try block using a return, a continue or a break statement 2. a normal completion happens when the try-catch-finally statement executes normally without any error occurring 3. the program code may have specified in a particular catch block the exception that was thrown 4. the exception thrown was not specified in any catch block

28 Throwing Exceptions Besides catching exceptions, Java also allows user programs to throw exceptions (i.e., cause an exceptional event to occur). The syntax for throwing exceptions is simple. Here is it. throw ;

29 Throws Keyword In the case that a method can cause an exception but does not catch it, then it must say so using the throws keyword. This rule only applies to checked exceptions. Here is the syntax for using the throws keyword: ( ) throws { }

30 Throws keyword A method is required to either catch or list all exceptions it might throw, but it may omit those of type Error or RuntimeException, or their subclasses.

31 Exception Classes and Hierarchy As mentioned earlier, the root class of all exception classes is the Throwable class. Presented below is the exception class hierarchy. These exceptions are all defined in the java.lang package.

32

33 Now that you’re quite familiar with several exception classes, it is time to introduce to this rule: Multiple catches should be ordered from subclass to superclass.

34 Check and Unchecked Exceptions An exception is either checked or unchecked. A checked exception is just an exception that is checked by Java compiler. The compiler makes sure that the program either catches or lists the occurring exception in the throws clause. If the checked exception is neither caught nor listed, then a compiler error will occur.

35 Check and Unchecked Exceptions Unlike checked exceptions, unchecked exceptions are not subject to compile-time checking for exception handling. The built- in unchecked exception classes are Error, RuntimeException, and their subclasses. Thus, these type of exceptions are no longer checked because handling all such exceptions may make the program cluttered and may most likely become a nuisance.

36 User-defined Exception You can also create your own Exception by just making your own exception class extends any built-in exception classes. Ex. class HateStringException extends RuntimeException{ public HateStringException(String msg){ super(msg); }

37 Assertion Assertions allow the programmer to find out if an assumption was met. For example, a date with a month whose range is not between 1 and 12 should be considered as invalid. The programmer may assert that the month should lie between this range. The nice thing about assertions is that the user has the option to turn it off or on at runtime.

38 Assertion Syntax The assert statement has two forms. The simpler form has the following syntax: assert ; where is the condition that is asserted to be true.

39 Assertion Syntax The other form uses two expressions and the syntax for this format is shown below. assert : ; where is the condition that is asserted to be true and is some information helpful in diagnosing why the statement failed.

40 Summary When an exception occurs, Java creates an objects that contains the information for the exception. You can use the information to handle the exception. A Java exception is an instance of a class derives from java.lang.Throwable. Java provides a number of predefined exception classes, such as Error, Exception, RuntimeException, ClassNotFoundException, NullPointerException, and ArithmeticException. You can also define your own exception class by extending Exception.

41 Summary Exception occur during the execution of a method. RuntimeException and Error are unchecked exceptions; all other exceptions are checked. When declaring a method, you have to declare a checked exception if the method might throw it, thus telling the compiler what can go wrong.

42 Summary The keyword for declaring an exception is throws, and the keyword for throwing an exception is throw. To invoke the method that declares checked exceptions, you must enclose the method call in a try statement. When an exception occurs during the execution of the method, the catch block catches and handles the exception.

43 Summary If an exception is not caught in the current method, it is passed to its caller. The process is repeated until the exception is caught or passed to the main method. Various exception classes can be derived from a common superclass. If a catch block catches the exception objects of a superclass, it can also catch all the exception objects of the subclasses of that superclass.

44 Summary The order in which exceptions are specified in a catch block is important. A compilation error will result if you do not specify an exception object of a class before an exception object of the superclass of that class.

45 Summary The code in the finally block is executed under all circumstances, regardless of whether an exception occurs in the try block or is caught. Exception handling should not be used to replace simple tests. You should test simple exceptions whenever possible, and reserve exception handling for dealing with situations that cannot be handled with if statements.


Download ppt "Exceptions Handling Prepared by: Ligemm Mae del Castillo."

Similar presentations


Ads by Google