Intermediate Java II 95-713 Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
Error Handling with Exceptions Concepts C and other earlier languages often had multiple error-handling schemes, and these were generally established.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 28 More on 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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 9: Exception Handling, I/O.
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.
DATA STRUCTURES Lecture: Exceptions, IO Slides adapted from Prof. Steven Roehrig CS
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
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.
CIS 270—Application Development II Chapter 13—Exception Handling.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
COMP Exception Handling Yi Hong June 10, 2015.
Introduction to Exception Handling and Defensive Programming.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
MCS 270 Spring 2014 Object-Oriented Software Development.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Exceptions 10-Nov-18.
Exceptions Handling the unexpected
Exceptions 10-May-19.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Intermediate Java II Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig

Today’s Topics  Older, and more modern, strategies for error handling.  Exception handling basics.  Some exception details: plain Exceptions vs. RuntimeExceptions Exceptions containing information Exception hierarchies  What’s really practical using exceptions.

Exception Handling  The compiler is supposed to report syntax errors, it but can’t discover many other types of errors: casts to the wrong type files that don’t exist dividing by zero indexing out of bounds incorrect data formats badly formed SQL queries etc. etc.  Unresolved, many of these errors prevent a program from continuing correctly.

Exception Handling  We would like to be aware of these “exceptional” situations, in hopes of recovery retrying trying an alternate strategy cleanup before exit or, just finding out where the problem is!  Nothing is more mystifying than a program that just “goes up in smoke”!

Strategies for Error Handling  In the course of programming, we constantly test for situations that routinely arise.  We include logic to deal with the possibilities (switch, if-else, etc.).  “Exceptional” situations are different. They are things that “should never happen”.  We expect our code will be free from bugs, but…  We’re usually wrong.

Strategies for Error Handling  Pre-testing the arguments to each function call.  Checking return values indicating error.  Setting and checking global error variables.  These are not formal methods, not part of the programming language itself.  They require programmer discipline (but so does the use of exceptions…).

Example void workOnArray(double[] myArray, int otherInfo) { int i = 0; // complicated calculation of array index i, using otherInfo myArray[i] = ; // what if i is out of bounds? }

Example (cont.) int workOnArray(double[] myArray, int otherInfo) { int i = 0; // complicated calculation of array index i, using otherInfo if (i >= 0 && i < myArray.length) { myArray[i] = ; return 0; // indicating everything OK } else return -1; // indicating an error }

Potential Problem  What if workOnArray() needs to return a value (say, a double)?  The “C” approach: values are returned through additional reference arguments in the method – not directly in Java.  This quickly gets cumbersome.

Another Technique: Globals  There are no true global variables in Java, but we “fake it” all the time.  Write a class with static variables!  These are effectively available anywhere in a program, and could be used to signal error conditions.

Faking A Global Variable public class MyGlobal { public static int indexError; MyGlobal() { } // indexError automatically initialized to 0 } void workOnArray(double[] myArray, int otherInfo) { int i = 0; // complicated calculation of array index i, using otherInfo if (i >= 0 && i < myArray.length) { myArray[i] = ; } else MyGlobal.indexError = -1; }

Three Important Issues  Where should the tests be done? Before the array is “indexed into”? By the array class itself?  Where should the error be reported? Locally, or “further down” in the call stack? Stroustrup says that authors of libraries can’t know their user’s contexts, so can’t know what to do.  Who is responsible for adjudicating the error?  Exception handling in Java helps with these problems, but doesn’t completely solve them.

Example class MyException extends Exception { MyException(String message) { MyException(String message) { super(message); super(message); }} class MyExceptionThrower { void f() throws MyException { void f() throws MyException { throw new MyException("Throwing MyException"); throw new MyException("Throwing MyException"); }}

Example, cont public static void main(String[] args){ MyExceptionThrower t = new MyExceptionThrower(); MyExceptionThrower t = new MyExceptionThrower(); try { try { t.f(); t.f(); } catch (MyException e) { catch (MyException e) { e.printStackTrace(); e.printStackTrace(); } finally { finally { System.out.println("Done"); System.out.println("Done"); } }

Some Points  f() must have “throws MyException”. Otherwise, compiler will complain.  The compiler insists any call to this method be “tested” by enclosing it in a try block, or else we get an “unreported exception” error.  If we do include a try block, there has to be a corresponding catch block or finally clause.  When an exception is thrown, control goes to the matching catch block.

More Points  All of this is true because our exception extended the Exception class.  If we extend RuntimeException instead, we don’t need to say throws, nor include try and catch blocks.  RuntimeExceptions are special; the Java runtime system takes care of them automatically.

Exceptions Always Get Caught public class NeverCaught { static void g() { static void g() { throw new RuntimeException(“From g()”); throw new RuntimeException(“From g()”); } static void f() { static void f() { g(); g(); } public static void main(String[] args) { public static void main(String[] args) { f(); f(); }}

“Uncaught” Exceptions  If an exception makes it all the way “back” to main() without being caught, the Java runtime system calls printStackTrace() and exits the program:  You can call printStackTrace() yourself if you want (and it’s useful to do it). java.lang.RuntimeException: From g() at NeverCaught.f(NeverCaught.java:5) at NeverCaught.g(NeverCaught.java:8) at NeverCaught.main(NeverCaught.java:11) Exception in thread "main"

Call Stack, Normal Execution main() called main() f() called f() g() called f() g() g() finished f() f() finished time

Call Stack, With Exception main() called main() f() called f() g() called f() g() f() exception thrown, g() has no handler, exit g() search f() for handler, exit f() search main() for handler, call printStackTrace(), exit main()

Catching Any Exception  We are always interested in exceptions that implement the interface Exception.  So, a catch block like catch(Exception e) { System.out.println(“Caught an exception”); } will catch any exception.  If you have multiple catch blocks, this one should be last.

Multiple Catch Blocks  There may be several possible errors generated by a block of code: try { // try this // and this } catch(YourException e) { System.out.println(“Caught exception defined by you”); } catch(Exception e) { System.out.println(“Caught some other exception”); }

Rethrowing an Exception  Suppose you’ve caught an exception, and decided you can’t recover from it, but perhaps a higher context can.  You can rethrow it: catch(Exception e) { System.out.println(“An exception was caught”); throw e; }  The stack trace remains unchanged if it is caught higher up.

Catching, Fixing and Retrying public class Retry { static int i = 0; public void f() { try { g(); } catch(Exception e) { System.out.println("Caught exception, i = " + i); i++; f(); } void g() throws gException { if (i < 3) { throw new gException(); } else System.out.println("g() is working now"); }

This Can Be Dangerous public class Retry { int i = 0; boolean fileIsOpen = false; public void f() { try { if (fileIsOpen) System.out.println("Opening an already opened file!"); else fileIsOpen = true;// i.e., open the file g(); fileIsOpen = false;// i.e., close the file } // file will be left open: Dangerous!

What’s So Dangerous?  Just close the file in the catch block? Good idea! But, what if some other exception were thrown, one that you didn’t catch? catch(gException e) { System.out.println("Caught exception, i = " + i); i++; fileIsOpen = false; f(); } finally { fileIsOpen = false; }

Exception Hierarchies  Exceptions are classes, so can be in inheritance hierarchies.  The usual polymorphism rules apply.  A handler for a superclass exception will catch a subclass exception.  This makes it easy to catch groups of exceptions.  Exceptions are real objects (created with new), and so can have constructors and data members.

Termination Vs. Resumption  Java makes it hard to complete this cycle: find a problem, throw an exception, fix the problem in the handler, and go back to where you left off.  This is called “resumption”.  Java assumes you don’t want to go back.  This is called “termination”.

What You Can Do  Fix the problem and call the method that caused the exception once more.  “Patch things up” and continue without retrying the method.  Calculate some alternative result.  Do what you can in the current context, and rethrow the same exception to a higher context.  Do what you can, and throw a different exception to a higher context.  Terminate the program (how?).