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.

Slides:



Advertisements
Similar presentations
1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
Exception Handling.  What are errors?  What does exception handling allow us to do?  Where are exceptions handled?  What does exception handling facilitate?
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Web Design & Development Lecture 7
CSE 143 Java Exceptions 1/18/2019.
Lecture 11 Objectives Learn what an exception is.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Chapter 12 Exception Handling and Text IO Part 1
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

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 mechanism. n Using Exception class and its subclasses. n Generating exceptions.

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.

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.

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.

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.

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.

The Java exception mechanism (cont.)

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.

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.

The Java exception mechanism (cont.)

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

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

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.

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);

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.

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.

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)

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.

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.

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.

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); … }

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; }

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.

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; }

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); }

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); }

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; }

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

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.

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.); }

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()); … }

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.

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.); }

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.

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).

Glossary