Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.

Similar presentations


Presentation on theme: "Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions."— Presentation transcript:

1 Chapter 8 Exceptions

2 Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions

3 Exceptions An exception represents an error condition that can occur during the normal course of program execution. –see Ch8Sample1 When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

4 Handling Exceptions We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop. One way to do this is to wrap the statements that may throw an exception with the try- catch control statement.

5 Catching Exceptions inputStr = JOptionPane.showInputDialog(null, prompt); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, “’” + inputStr +‘ is invalid\n” +“Please enter digits only”);

6 Execution Sequence Statements in the try block are executed in sequence. When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed. The execution then continues to the statement following the try-block statement, ignoring any remaining statements in the try block. If no statements in the try block throw an exception, the catch block is ignored. Execution continues with the statement following the try- catch statement.

7 try-catch Control Flow try-catch statement with one catch block.

8 Throwable Methods There are two methods of the Throwable class we can call to get information about the thrown exception: –getMessage –printStackTrace

9 Run-Time Stack The run-time stack is what is used to keep track of the methods that are currently being executed. When you call a method, the system puts the parameter data and the location the method was called from on the top of a data structure called a stack. When the method finishes, this data is removed from the stack and the calling method continues at the line the method was called from.

10 Throwing Exceptions An exception can be thrown in a program using the throw statement. throw –where is an instance of the Throwable class or its subclasses.

11 Catching Exceptions When there are multiple catch blocks in a try- catch statement, they are checked in sequence. It is important to check more specialized exception classes before the more general exception classes. When an exception is thrown, its matching catch block is executed and the other catch blocks are ignored.

12 try-catch Control Flow try-catch statement with multiple catch blocks.

13 Which catch Block? If none of the catch blocks matches the thrown exception, the system will search down the stack trace for a method with a matching catch block. If none is found, the system will handle the thrown exception.

14 The finally Clause If there is a block of code that must be executed regardless of whether an exception is thrown, we use the reserved word finally. inputStr = JOptionPane.showInputDialog(null, “”); try{ number = Integer.parseInt(inputStr); if (num>100) { throw new Exception(“Out of bound”); } } catch (NumberFormatException e) { System.out.println(“Cannot convert to int”); } catch (Exception e) { System.out.println(“Error: ” + e.getMessage()); } finally { System.out.println(“DONE”); }

15 finally The finally block is executed even if there is a return statement inside the try block. –When the return statement is encountered in the try block, statements in the finally block are executed before actually returning from the method.

16 try-catch Control Flow try-catch statement with multiple catch blocks and the finally block.

17 Propagating Exceptions When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: –An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. –An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.

18 Exception Propagation The figure on the next slide shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.

19 Exception Propagation public A() { try { B() } catch (Exception e) { … } } public B() { try { C() } catch (Exception e) { … } } public C() { D();} public D() { if (cond)throw new Exception(); }

20 throws Clause If a method is an exception propagator, we need to modify its header to declare the type of exceptions the method propagates. We use the reserved word throws for this declaration. void C( ) throws Exception {... } Without the required throws Exception clause, the program will not compile. However, for the exception of the type called runtime exceptions, the throws clause is optional.

21 Propagating Exceptions Do not catch an exception that is thrown as a result of violating a condition set by the client programmer. Instead, propagate the exception back to the client programmer’s code and let him or her handle it.

22 Types of Exceptions All types of thrown errors are instances of the Throwable class or its subclasses. –Serious errors are represented by instances of the Error class or its subclasses. –Exceptional cases that common applications should handle are represented by instances of the Exception class or its subclasses.

23 Throwable Classes Partial inheritance hierarchy. There are over 60 classes in the hierarchy.

24 Types of Exceptions There are two types of exceptions: –Checked. –Unchecked. A checked exception is an exception that is checked at compile time. All other exceptions are unchecked exceptions, –Also known as runtime exceptions.

25 Checked Exceptions If a method is a propagator of checked exceptions, the method must have the throws clause. When calling a method that can throw checked exceptions, do one of the following – use the try-catch statement and place the call in the try block –modify the method header to include the appropriate throws clause.

26 Checked Exceptions Callers of a method that can throw a checked exception must include the try- catch statement in the method body or the throws clause in the header. void callerA() { try { doWork(); } catch (Exception e) { … } void callerB() throws Exception { … doWork(); … } public void doWork() throws Exception { … throw new Exception(); … }

27 Unchecked Exceptions Callers of a method that can throw runtime exceptions may include the try-catch statement in the method body or the throws clause in the header. void callerA() { try { doWork(); } catch (RuntimeException e) { … } void callerB() throws RuntimeException { … doWork(); … } void callerC() { … doWork(); … } public void doWork() { … throw new RuntimeException(); … }

28 Catching Exceptions We must specify which exception we are catching in the catch block’s parameter list. In Java an exception is represented as an instance of the Throwable class or its subclasses. The Throwable class has two subclasses: –Error - the Error class represents serious problems that should not be caught by ordinary applications. –Exception - the Exception class represents error conditions that can be caught and handled.

29 Programmer-Defined Exceptions Instead of using generic exception classes, we can define our own exception classes and attach useful information to the exception objects. When creating a new customized exception class, define it as a checked exception to ensure client programmers handle thrown exceptions of this class in their code.

30 Assertions Assertions provide a way to detect internal programming errors. The syntax for the assert statement is assert ; –where represents the condition that must be true if the code is working correctly. If the expression results in false, an AssertionError (a subclass of Error) is thrown.

31 Types of Assertions Precondition assertions check for a condition that must be true before executing a method. Postcondition assertions check conditions that must be true after a method is executed. A control-flow invariant is a third type of assertion, under which control must flow to one of a number of particular cases.

32 Supervisor-Subordinate Design Pattern In a client-service design model, the client calls the method of a service object, and the service object carries out the requested operation. The supervisor-subordinate design pattern is similar to, but more sophisticated than, the client-service model.

33 Supervisor-Subordinate Design Pattern In the supervisor-subordinate design pattern, the supervisor object controls a subordinate object, but the subordinate can also call the supervisor’s method. To implement this design pattern, we must establish mutual references between the supervisor and subordinate.

34 Supervisor-Subordinate Example class Supervisor { private Subordinate worker; public Supervisor ( ) {... worker = new Subordinate(this);... }... } class Subordinate { private Supervisor boss; public Subordinate(Supervisor boss) {... this.boss = boss;... }... }

35 Supervisor-Subordinate Design Pattern When a new supervisor object is created, the subordinate is created also, and the mutual references are established as follows:


Download ppt "Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions."

Similar presentations


Ads by Google