CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.

Slides:



Advertisements
Similar presentations
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Handling errors Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main concepts to be covered.
For use of Cleveland State's IST410 Students only 1 Exception.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
11-Jun-15 Exceptions. 2 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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
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.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
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. 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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
Handling errors Writing robust code. 16/12/2004Lecture 10: Handling Errors2 Main concepts to be covered Defensive programming. –Anticipating that things.
CPSC150 Week 13 Chapter 12 Exceptions (from slides provided by textbook web site)
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
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.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Handling errors Exception handling and throwing Simple file processing.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Objects First With Java A Practical Introduction Using BlueJ Handling errors 1.0.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Fundamental Error Handling
Web Design & Development Lecture 7
Exceptions 19-Feb-19.
Exceptions 25-Apr-19.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
Presentation transcript:

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things go TRAGICALLY AWRY

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 2 CPSC150 How things go TRAGICALLY AWRY User enters bad data Programmer makes a mistake Another method/program passes bad data to a method System problems happen

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 3 CPSC150 When others use your program Check values being returned are reasonable. Don't do actions that will cause problems Create return value that indicates a problem so clients can: –Attempt recovery on error –Avoid program failure –Ignore the return value Cannot be prevented Likely to lead to program failure Create something client cannot ignore: –an exception

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 4 CPSC150 Exception-throwing principles Exceptions are part of many languages, central to Java. A special language feature. No ‘special’ return value needed. Errors cannot be ignored in the client. –The normal flow-of-control is interrupted. Specific recovery actions are encouraged.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 5 CPSC150 Exceptions Exceptions are “thrown” by the method finding the problem Exceptions are “caught” by the method dealing with the problem maintains integrity and decoupling

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 6 CPSC150 The effect of an exception The throwing method finishes prematurely. No return value is returned. Control does not return to the client’s point of call. –So the client cannot carry on regardless. A client may ‘catch’ an exception.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 7 CPSC150 Throwing an exception public void setDenominator(int den) { if(den == 0) { throw new Exception(“Divide by 0"); } denominator = den; }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 8 CPSC150 Throwing an exception An exception object is constructed: –new ExceptionType("..."); –Most often, use existing Exception types The exception object is thrown: –throw... –Most often, exception is thrown by java classes, not programmer-defined

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 9 CPSC150 Error recovery Clients should take note of error notifications. –Check return values. –Don’t ‘ignore’ exceptions. Include code to attempt recovery. –Will often require a loop.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 10 CPSC150 Handling Exceptions: The try-catch statement Clients catching an exception must protect the call with a try statement: try { // put statements here that might throw an // exception } catch(Exception e) { // Report and recover from the // exception here. }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 11 CPSC150 The try-catch statement 1. Exception thrown from here 2. Control transfers to here Fraction f; try { f.setDenominator(n); // n is an already defined with a value } catch (ArithmeticException ex) { System.out.println("you dummy, use something other than 0"); }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 12 CPSC150 try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 13 CPSC if method call, do method try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception Order of statement execution 2a. continue with rest of try 3a. skip catch, do code after try- catch Case a: no exception thrown

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 14 CPSC150 try { // code that might throw an exception } catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception Order of statement execution 1. if method call, do method 2b. skip rest of try; do code in catch 3b. if catch code does not abort program, continue after catch block Case b: TypeOfException thrown

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 15 CPSC150 try { // code that might throw an exception { catch (TypeOfException ex) { // what to do when there is a problem } // what to do afterwards regardless of // whether there was an exception Order of statement execution 1. if method call, do method 2c. skip rest of try; do not do catch; exit from this method at the code in try; do not do any other code 3c. No other code in this method is executed. catch code and code afterwards is skipped Case c: DifferentException thrown

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 16 CPSC150 public class George { private int x; public George() { x = 0; } public int divideByY(int y) { if (y == 0) { throw new ArithmeticException( "in divideByY, y, a denominator, is 0"); } y= x /y; return y; } An Exception Example

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 17 CPSC150 Write a main method that calls divideByY Write a main method that has try-catch block

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 18 CPSC150 public static void main(String[] args) { George m = new George(); System.out.println("m with 4 is " + m.divideByY(4)); System.out.println("m with 0 is " + m.divideByY(0)); System.out.println("all done"); } // end main } // end class

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 19 CPSC150 public static void main(String args[ ]) { George m = new George(); try { System.out.println("m with 4 is " + m.divideByY(4)); System.out.println("m with 0 is " + m.divideByY(0)); } catch (ArithmeticException e) { System.out.println("don't call method with 0 as parameter"); e.printStackTrace(); } System.out.println("all done"); }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 20 CPSC150 Try-Catch second chance Can put try-catch blocks in a loop. –if catch block not entered, exit loop –if catch block entered, print a message; ask the user to fix the problem –if catch block entered too many times, give up

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 21 CPSC150 public class Test { public static void main(String args[]) { int n = 0; Scanner kbd = new Scanner(System.in); int mynbr; String s = null; boolean valid = false; while (!valid && n<3) { try { System.out.print(“Enter an integer: ”); mynbr = kbd.nextInt( ); valid = true; } catch (Exception georgette) { System.out.print(“You must enter a valid integer-> ”); n++; } }// end of loop if (valid) System.out.println("The number is " + mynbr ); }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 22 CPSC150 Catching multiple exceptions tried in order that they appear try {... ref.process();... } catch(EOFException e) { // Take action on an end-of-file exception.... } catch(IOException e) { // Take action on any other IOexception.... }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 23 CPSC150 The finally clause try { Protect one or more statements here. } catch(Exception e) { Report and recover from the exception here. } finally { Perform any actions here common to whether or not an exception is thrown. }

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 24 CPSC150 The finally clause: why A finally clause is executed even if a return statement is executed in the try or catch clauses. A uncaught or propagated exception still exits via the finally clause.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 25 CPSC150 The exception class hierarchy

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 26 CPSC150 Exception categories Checked exceptions: extra syntax required –Subclass of Exception –Use for anticipated failures. –Where recovery may be possible. –Often not a programming problem (e.g., file not found) Unchecked exceptions: extra syntax NOT required –Subclass of RuntimeException –Use for unanticipated failures. –Where recovery is unlikely. –Often, a programming problem (e.g., index out of bounds) Third category: errors

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 27 CPSC150 Checked Exceptions Previous examples all unchecked exceptions Checked exceptions are meant to be caught. The compiler ensures that their use is tightly controlled. –In both server and client. Used properly, failures may be recoverable.

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 28 CPSC150 Some Checked Exceptions –ClassNotFoundExceptionClassNotFoundException –IOExceptionIOException –NoSuchFieldExceptionNoSuchFieldException –ServerNotActiveExceptionServerNotActiveException –UnsupportedFlavorExceptionUnsupportedFlavorException

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 29 CPSC150 The throws clause Methods throwing a checked exception must handle the exception or include a throws clause: public void saveToFile(String destinationFile) throws IOException (NOT throw) throw is when the exception is thrown

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 30 CPSC150 throws must include throws in methods that throw checked exceptions how do I know? javadoc/syntax errors

CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 31 CPSC150 Text input-output: tie to exceptions java.io.IOException is a checked exception. cannot do files without exceptions