Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.

Similar presentations


Presentation on theme: "Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception."— Presentation transcript:

1 Chapter 17 Failures and exceptions

2 This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception mechanism. n Using Exception class and its subclasses. n Generating exceptions.

3 Failure n Inability of a system, at run-time, to accomplish its intended purpose. n A method can fail for two reasons: u A logical error in its implementation. u Its inability to obtain some needed resource from the environment. n Programs containing an error can do little about it at run-time, except offer a helpful error message that will assist in identifying and locating the problem.

4 Failure (cont.) n A system may need resources from u the hardware, u the operating system, u the file system, u the network, u a data base, or u a user to achieve its purpose. n The system may be unable to provide the needed resource.

5 Failure (cont.) n exception: The occurrence of a detectable, abnormal situation which may lead to system failure. n We can design programs so that the program itself will detect some logical errors.

6 The Java exception mechanism n The exception mechanism includes the facilities for detecting, reporting, and handling exceptions. n The exception mechanism should not be used to handle normal, expected events. n It is not just another control structure. n The Java run-time system or interpreter detects certain run-time errors, such as attempts to divide by zero or to use a null reference when an object is required. n The system notifies the program of the error by throwing an exception from the point at which the error occurred.

7 The Java exception mechanism (cont.) n A thrown exception involves a transfer of control: the processor stops executing the current sequence of statements, and begins executing statements at a different point in the program. n The exception is caught or handled at the point to which control is transferred.

8 The Java exception mechanism (cont.)

9 n An exception is modeled as an instance of the Java class Throwable. n The Error class and its subclasses represent conditions from which an ordinary program is not expected to recover.

10 The Java exception mechanism (cont.) n A few standard exceptions which are subclasses of RuntimeException: u ArithmeticException: an exceptional arithmetic situation has arisen, such as an integer division with zero divisor. u ClassCastException: an attempt made to cast a reference to an inappropriate type. u IllegalArgumentException: a method was invoked with an invalid or inappropriate argument, or an inappropriate object. u NullPointerException: an attempt was made to use a null reference in a case where an object reference was required. u SecurityException: a security violation was detected.

11 The Java exception mechanism (cont.)

12 Catching exceptions try { statements1 } catch ( exception parameter1 ) { statements2 } catch ( exception parameter2 ) { statements3 } …

13 Catching exceptions (cont.) try { statements1 } catch ( ArithmeticExection e) { statements2 } catch ( NullPointerException e ) { statements3 } catch ( Exception e ) { statements4 }

14 Catching exceptions (cont.) n The processor first performs the statements of the try block. u If no exceptions occur, the try-catch is complete, and the catch clauses are ignored. u If an exception is thrown during execution of the try block, an attempt is made to match the exception to the catch clause parameters.

15 Catching exceptions (cont.) try { i = i/i; j = 0; name = s.name(); j = 1; } catch (ArithmeticException e) { j = 3; } catch (NullPointerException e) { j = 4; } catch (Exception e) { if (e instanceof IllegalArgumentException) j = 6; else j = 5; } System.out.println(The value of j is + j);

16 Propagated exceptions n If an exception is thrown by the execution of a statement that is not part of a try-catch, or if an exception is generated that does not match any of the catch clauses, the exception is propagated up the call chain to the calling method.

17 Checked and unchecked exceptions n The class RuntimeException and its subclasses are referred to as unchecked exception classes. n Other exception classes are checked exception classes. n A methods specification must explicitly state if it is possible for the method to throw a checked exception to its caller.

18 Checked and unchecked exceptions (cont.) public String readline() throws IOException (An IOException is propagated to readLines caller) public void skip () throws IOException { String s; s = input.readLine(); } public void skip () throws EOFException, FileNotFoundException { … } (can propagate more than one kind of exception)

19 Using exceptions n The server promises to fulfill a contract only if the client satisfies the preconditions. public int indexOf (Object item) The index of the first occurrence of the specified item on this List, or -1 if this List does not contain the specified item. n If we removed the specification of returning a -1 if the item was not found in the list, we would need to have a precondition that the item be found in the list. n This puts an unreasonable burden on the client.

20 Contract failures n A method fails if it is unable to complete a contract even though its client has satisfied all preconditions. n Three failure cases: u A logical error in the method. u The method is not able to obtain necessary resources. u The method invokes another method which fails.

21 Dealing with exceptions n There are only two ways of dealing with failure of logical structures. u Clean up and report the failure to the caller (by throwing an exception). u Attempt to correct the situation that caused the exception, and try again.

22 FileReader example n A class java.io.FileReader constructor is specified as follows. public FileReader (String fileName) throws FileNotFoundException, SecurityException SecurityException is an unchecked exception, but is something we wish to address. public void getSomeData() throws FileNotFoundException,SecurityException{ FileReader in; in = new FileReader (DataFile); … }

23 FileReader example (cont.) public void getSomeData () throws FileNotFoundException,SecurityException{ FileReader in; try { in = new FileReader (DataFile); … } catch (FileNotFoundException e) { //cleanup throw e; } } catch (SecurityException e) { //cleanup throw e; }

24 Cleanup n A method cannot know how its caller will respond to the exception. n The caller might be able to recover. n It is important that the method leave its object in a consistent state (with all class invariants satisfied). n A method should make sure that the object is consistent before reporting failure to its caller.

25 FileReader example (cont.) Suppose a file is locked, but we expect the lock to be removed shortly. public void getSomeData () throws FileNotFoundException,SecurityException{ FileReader in; boolean success = false;// Data file opened int tryNumber = 0 ; // # of attempts to open datafile int delay = 5 * 1000;//wait in millsecs while (!success) try { tryNumber = tryNumber + 1; in = new FileReader(DataFile); success = true; … } catch (SecurityException e) { if (tryNumber == 1) thisThread.sleep(delay); else throw e; }

26 Application defined exceptions n It is sometimes useful to define our own exception classes to pass certain information to the client. n Example: throw an exception if we fail for any reason to get data. public class NoDataException extends Exception { public NoDataException () { super(); } public NoDataException (String s) { super(s); }

27 Application defined exceptions (cont.) public void getSomeData () throws NoDataException { try { in = new FileReader(DataFile); … } catch (FileNotFoundException e) { //cleanup throw new NoDataException (File does not exist) } catch (SecurityException e) { //cleanup throw new NoDataException (File cannot be accessed); }

28 Application defined exceptions (cont.) n An exception class also can pass state information from the method detecting the exception to the method that will handle it. public class BadDataException extends Exception { public BadDataException (int lineNumber) { super(); this.lineNumber = lineNumber; } public int lineNumber() { return this.lineNumber; } private int lineNumber; }

29 Exceptions n Exception objects are structured as immutable objects: their interface includes no state-changing commands.

30 Dealing with logical errors n Sometimes a logical error causes a method to produce reasonable but incorrect results. n We can check preconditions, postconditions, and invariants. n If a client invokes a method without preconditions being satisfied, it is an error.

31 Dealing with logical errors (cont.) public class PreconditionException extends RuntimeException Failure because a precondition is not satisfied. public class Require { static public void condition (boolean precondition) { if (!precondition) throw new PreconditionException (Precondition not satisfied.); } static public void notNull (Object reference) { if (reference == null) throw new PreconditionException (Null reference.); }

32 Dealing with logical errors (cont.) /** * Interchange l.get(i) and l.get(j) * require: * 0 <= i,j < l.size() */ private void interchange (List l, int i, int j) { Require.condition(0 <= i && i < l.size()); Require.condition(0 <= j && j < l.size()); … }

33 Dealing with logical errors (cont.) public class PostconditionException extends RuntimeException Failure because a postcondition is not satisfied. public class Ensure { static public void condition (boolean postcondition){ if (!postcondition) throw new PostconditionException (Postcondition not satisfied.); } n Postconditions can be tricky to handle; often they involve comparing an objects state after method execution to the objects state prior to execution.

34 Dealing with logical errors (cont.) public class AssertionException extends RuntimeException Failure because an assertion is not satisfied. public class Assert { static public void condition (boolean condition){ if (!condition) throw new AssertionException (Assertion not satisfied.); }

35 Dealing with logical errors (cont.) n Postconditions and invariants often are too complex to verify with a simple condition. n Whether to include such checks depends to a large degree on where we are in the development process.

36 Weve covered n Method failure due to u A logical error in its implementation. u Its inability to obtain some needed resource from the environment. n The exception mechanism u Detecting, reporting, handling failure. n The try-catch statement. n When a client is notified of a servers failure, the client can u Attempt to correct the situation. u Report failure to its caller(more practical).

37 Glossary


Download ppt "Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception."

Similar presentations


Ads by Google