Chapter 05: Exception Handling PDF

Document Details

FineEnlightenment390

Uploaded by FineEnlightenment390

Wachemo University College of Natural and Computational Science

Tags

exception handling java programming computer science

Summary

This document is a chapter on exception handling in Java, covering compile-time and runtime errors, exception hierarchies, and handling mechanisms. It includes illustrative examples.

Full Transcript

CHAPTER 05 Exception Handling 1 Objectives After studying this chapter, students should be able to learn: Exception Exception Hierarchy Exception Handling Throwing Exception User-defined Exceptions Introduct...

CHAPTER 05 Exception Handling 1 Objectives After studying this chapter, students should be able to learn: Exception Exception Hierarchy Exception Handling Throwing Exception User-defined Exceptions Introduction An error in a program is called bug. Removing errors from program is called debugging. Errors are broadly classified into 2 types: – Compile-time Errors: Errors which occur due to syntax or format is called compile time errors. These errors are detected by java compiler at compilation time. The.class file will not be created due to errors. Most of the compile-time errors are due to typing mistakes. Examples: missing semicolon, missing double quotes, use of undeclared variables etc. – Run-time Errors: These are the errors that represent computer inefficiency. Insufficient memory to store data or inability of the microprocessor to execute some statement is examples to runtime errors. Runtime errors are detected by JVM at runtime. Examples: division by zero, accessing an element that is out of the array bound, converting invalid strings to integer etc. Exception An abnormal event in a program is called an Exception. Exception may occur at compile time or at runtime. Exceptions which occur at compile time are called Checked exceptions. – Ex: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc. Exceptions which occur at run time are called Unchecked exceptions. – Ex: ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException etc. Exception Hierarchy All exceptions are sub-classes of the built-in class Throwable. Throwable contains two immediate sub-classes: 1. Exception – exceptional conditions that programs should catch. The class includes: a) RuntimeException – defined automatically for user programs to include: division by zero, invalid array indexing, etc. b) user-defined exception classes 2. Error – exceptions used by Java to indicate errors with the runtime environment; user programs are not supposed to catch them Hierarchy of Exception Classes Checked Exceptions Inherit from class Exception but not from RuntimeException Compiler enforces catch-or-declare requirement Compiler checks each method call and method declaration – determines whether method throws checked exceptions. – If so, the compiler ensures checked exception caught or declared in throws clause. – If not caught or declared, compiler error occurs. Some Common Checked Exceptions 1. NoSuchMethodException 2. NoSuchFieldException 3. InterruptedException 4. InstantiationException 5. IllegalAccessException 6. CloneNotSupportedException 7. ClassNotFoundException Checked Exceptions import java.io.*; class Expdemo { public static void main(String args[]) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int a = Integer.parseInt(br.readLine()); int b = Integer.parseInt(br.readLine()); System.out.println("Sum is :"+(a+b)); } } Expdemo.java:9: unreported exception java.io.IOException; must be caught or declared to be thrown int a = Integer.parseInt(br.readLine()); Expdemo3.java:10: unreported exception java.io.IOException; must be caught or declared to be thrown int b = Integer.parseInt(br.readLine()); Unchecked Exceptions Inherit from class RuntimeException or class Error Compiler does not check code to see if exception caught or declared If an unchecked exception occurs and not caught – Program terminates or runs with unexpected results Can typically be prevented by proper coding Some Common Unchecked Exceptions 1. ArithmaticException (Divide By 0) All Unchecked Exceptions 2. ArrayIndexOutOfBoundsException directly or indirectly are sub classes of RunTimeException 3. ArrayStoreException 4. FileNotFoundException 5. NullPointerException 6. NumberFormatException 7. IllegalArumentsException UncheckedExceptions Example class Exceptiondemo1 { public static void main(String args[]) throws ArithmeticException { int a=10; int b= 5; int c =5; int x = a/(b-c); // Dynamic Initilization No Need to mention for System.out.println("c="+c); Unchecked Exceptions int y = a/(b+c); System.out.println("y="+y); } Can Throw an Exception } C:\>javac Exceptiondemo1.java > C:\>java Exceptiondemo1 Exception in thread "main" java.lang.ArithmeticException: / by zero at Exceptiondemo1.main(Exceptiondemo1.java:8) Exception Handling Code that could generate errors put in try blocks – Code for error handling enclosed in a catch clause – The finally clause always executes Five constructs are used in exception handling: 1. try – a block surrounding program statements to monitor for exceptions 2. catch – together with try, catches specific kinds of exceptions and handles them in some way 3. finally – specifies any code that absolutely must be executed whether or not an exception occurs 4. throw – used to throw a specific exception from the program 5. throws – specifies which exceptions a given method can throw Exception Handler The statement that causes an exception is try block thrown from here The statement that handles the exception catch block Figure: Exception Handling mechanism Exception General form: Handling Blocks try { … // generates an exception } catch(Exception1 e1){ where: …//handles the exception 1. try { … } is the block of code to monitor } for exceptions catch(Exception2 e2){ … 2. catch(Exception ex) { … } is exception } handler for the exception Exception finally { 3. finally { … } is the block of code to … } execute before the try block ends Example class DivByZero { public static void main(String args[]) { try { int a = 10, b = 0, c; c = a / b; System.out.println("Division = " + c); }catch (ArithmeticException e) { System.out.println("Error:" + e.getMessage()); } } Output: } Error: / by zero Quit Example - Multiple catch Statements class MultipleCatch { public static void main(String args[]) { try { int a = 10, b = 0, c; c = a / b; System.out.println("Division = " + c); int x[] = {1, 2, 3}; x = 100; } catch (ArithmeticException e) { System.out.println("Error:" + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e2) { System.out.println("Error:" + e2.toString()); } } } Even though multiple exceptions are found in the program, only one exception is raised at a time. Nested try's class NestedTryDemo { public static void main(String args[]){ try { int a = Integer.parseInt(args); try { int b = Integer.parseInt(args); System.out.println(a/b); } catch (ArithmeticException e) { System.out.println(“Div by zero error!"); } } catch (ArrayIndexOutOfBoundsException e2) { System.out.println(“Need 2 parameters!"); } } } Throwing Exceptions(throw) So far, we were only catching the exceptions thrown by the Java system. In fact, a user program may throw an exception explicitly: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or its subclass. Once an exception is thrown by: throw ThrowableInstance; 1. the flow of control stops immediately 2. the nearest enclosing try statement is inspected if it has a catch statement that matches the type of exception: 3. if one exists, control is transferred to that statement 4. otherwise, the next enclosing try statement is examined 5. if no enclosing try statement has a corresponding catch clause, the default exception handler halts the program and prints the stack Contd. Two ways to obtain a Throwable instance: 1. creating one with the new operator All Java built-in exceptions have at least two constructors: One without parameters and another with one String parameter: throw new NullPointerException("demo"); 2. using a parameter of the catch clause try { … } catch(Throwable e) { …… } Example: class ThrowDemo { throw 1 //The method demoproc throws a NullPointerException //exception which is immediately caught in the try block and re-thrown: static void demoproc() { try { throw new NullPointerException("demo"); } catch(NullPointerException e) { System.out.println("Caught inside demoproc."); throw e; } } Example: throw 2 //The main method calls demoproc within the try block which catches and handles the NullPointerException exception: public static void main(String args[]) { try { demoproc(); } catch(NullPointerException e) { System.out.println("Recaught: " + e); } } } throws Declaration If a method is capable of causing an exception that it does not handle, it must specify this behavior by the throws clause in its declaration: type name(parameter-list) throws exception-list { … } where exception-list is a comma-separated list of all types of exceptions that a method might throw. All exceptions must be listed except Error and RuntimeException or any of their subclasses, otherwise a compile-time error occurs. Example: throws 1 The throwOne method throws an exception that it does not catch, nor declares it within the throws clause. class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } } Therefore this program does not compile. Example: throws 2 Corrected program: throwOne lists exception, main catches it: class ThrowsDemo { static void throwOne() throws IllegalAccessException{ System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } } finally When an exception is thrown: 1) the execution of a method is changed 2) the method may even return prematurely. This may be a problem in many situations. For instance, if a method opens a file on entry and closes on exit; exception handling should not bypass the proper closure of the file. The finally block is used to address this problem. finally Clause The try/catch statement requires at least one catch or finally clause, although both are optional: try { … } catch(Exception1 ex1) { … } … finally { … } Executed after try/catch whether or not the exception is thrown. Any time a method is to return to a caller from inside the try/catch block via: 1) uncaught exception or 2) explicit return the finally clause is executed just before the method returns. Example: finally 1 Three methods to exit in various ways. class FinallyDemo { //procA prematurely breaks out of the try by throwing an exception, the finally clause is executed on the way out: static void procA() { try { System.out.println("inside procA"); throw new RuntimeException("demo"); } finally { System.out.println("procA's finally"); } } Example: finally 2 // procB’s try statement is exited via a return statement, the finally clause is executed before procB returns: static void procB() { try { System.out.println("inside procB"); return; } finally { System.out.println("procB's finally"); } } Example: finally 3 In procC, the try statement executes normally without error, however the finally clause is still executed: static void procC() { try { System.out.println("inside procC"); } finally { System.out.println("procC's finally"); } } Creating Own Exception Classes Built-in exception classes handle some generic errors. For application-specific errors, define your own exception classes. How? Define a subclass of Exception: class MyException extends Exception { ……… } MyException need not implement anything – its mere existence in the type system allows to use its objects as exceptions. Example: Own Exceptions 1 A new exception class is defined, with a private detail variable, a one parameter constructor and an overridden toString method: class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } } Example: Own Exceptions 2 class ExceptionDemo { //The static compute method throws the MyException exception whenever its a argument is greater than 10: static void compute(int a) throws MyException { System.out.println("Called compute: " + a); if (a > 10) throw new MyException(a); System.out.println("Normal exit"); } Example: Own Exceptions 3 The main method calls compute with two arguments within a try block that catches the MyException exception: public static void main(String args[]) { Output: try Called compute(1) { Normal exit Called compute(20) compute(1); Caught MyException compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } Self -Review Questions 1. What is a package? How do we design a package? 2. How do we add a class or interface to a package? 3. Explain in detail about accessing a package. 4. Explain about the access protection in packages? 5. What is interface? Write a program to demonstrate how interfaces can be extended. 6. Does Java Support multiple inheritance? Write Java a program to implement the multilevel Inheritance.

Use Quizgecko on...
Browser
Browser