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.

Slides:



Advertisements
Similar presentations
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Advertisements

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.
COMP 121 Week 5: Exceptions and Exception Handling.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
Exceptions Exception. Exceptions Overview Exceptional Situations Syntax of Try, Catch, Throw Defining and Using Your Own Exceptions.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
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.
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.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
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.
Java Software Solutions Foundations of Program Design Sixth Edition
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.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
COMP Exception Handling Yi Hong June 10, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
(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. Agenda Exception. Handling Exceptions. The finally Clause.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
OOP Tirgul 7. What We’ll Be Seeing Today  Packages  Exceptions  Ex4 2.
Generics, Exceptions and Undo Command
Chapter 10 – Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exceptions & Error Handling
Chapter 12 Exception Handling
Web Design & Development Lecture 7
Exceptions 19-Feb-19.
Exceptions 7-Apr-19.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
CSC 143 Java Errors and Exceptions.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions.
Presentation transcript:

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 An exception is a problem whose cause is outside your program –trying to open a file that isn’t there –running out of memory

What to do about errors and exceptions An error is a bug in your program –It should be fixed An exception is a problem that your program may encounter –The source of the problem is outside your program –An exception is not the “normal” case, but... –...your program must be prepared to deal with it This is not a formal distinction–it isn’t always clear whether something should be an error or an exception

Dealing with exceptions Most exceptions arise when you are handling files –A needed file may be missing –You may not have permission to write a file –A file may be the wrong type Exceptions may also arise when you use someone else’s classes (or they use yours) –You might use a class incorrectly –Incorrect use should result in an exception

The problem with exceptions Here’s what you might like to do: –open a file –read a line from the file But here’s what you might have to do: –open a file –if the file doesn’t exist, inform the user –if you don’t have permission to use the file, inform the user –if the file isn’t a text file, inform the user –read a line from the file –if you couldn’t read a line, inform the user –etc., etc. All this error checking really gets in the way of understanding the code

Three approaches to error checking 1.Ignore all but the most important errors –The code is cleaner, but the program will misbehave when it encounters an unusual error 2.Do something appropriate for every error –The code is cluttered, but the program works better –You might still forget some error conditions 3.Do the normal processing in one place, handle the errors in another (this is the Java way) –The code is at least reasonably uncluttered –Java tries to ensure that you handle every error

The try statement Java provides a new control structure, the try statement (also called the try-catch statement) to separate “normal” code from error handling: try { do the “normal” code, ignoring possible exceptions } catch ( some exception ) { handle the exception } catch ( some other exception ) { handle the exception }

Exception handling is not optional As in other languages, errors usually just cause your program to crash Other languages leave it up to you whether you want to handle exceptions –There are a lot of sloppy programs in the world Java tries to force you to handle exceptions –This is sometimes a pain in the neck, but –the result is usually a better program

Error and Exception are Object s In Java, an error doesn’t necessarily cause your program to crash When an error occurs, Java throws an Error object for you to use –You can catch this object to try to recover –You can ignore the error (the program will crash) When an exception occurs, Java throws an Exception object for you to use –You cannot ignore an Exception ; you must catch it –You get a syntax error if you forget to take care of any possible Exception

The exception hierarchy Throwable : the superclass of “throwable” objects –Error : Usually should not be caught (instead, the bug that caused it should be fixed) –Exception : A problem that must be caught RuntimeException : A special subclass of Exception that does not need to be caught Hence, it is the Exception s that are most important to us (since we have to do something about them)

The Exception hierarchy II Throwable ErrorException RuntimeException Must be caught Need not be caught

Kinds of Exceptions IOException : a problem doing input/output –FileNotFoundException : no such file –EOFException : tried to read past the End Of File NullPointerException : tried to use a object that was actually null ( RuntimeException ) NumberFormatException : tried to convert a non-numeric String to a number ( RuntimeException ) OutOfMemoryError : the program has used all available memory ( Error ) There are about 200 predefined Exception types

What to do about Exceptions You have two choices: –You can “catch” the exception and deal with it For Java’s exceptions, this is usually the better choice –You can “pass the buck” and let some other part of the program deal with it This is often better for your own exceptions Exceptions should be handled by the part of the program that is best equipped to do the right thing about them

What to do about Exceptions II You can catch exceptions with a try statement –When you catch an exception, you can try to repair the problem, or you can just print out information about what happened You can “pass the buck” by stating that the method in which the exception occurs “throws” the exception –Example: void openFile(String fileName) throws IOException {... }

How to use the try statement Put try {...} around any code that might throw an exception –This is a syntax requirement you cannot ignore For each Exception object that might be thrown, you must provide a catch phrase: catch ( exception_type name ) {...} –You can have as many catch phrases as you need –name is a formal parameter that holds the exception object –You can send messages to this object and access its fields

How the try statement works The code in the try {...} part is executed If there are no problems, the catch phrases are skipped If an exception occurs, the program jumps immediately to the first catch clause that can handle that exception

Ordering the catch phrases A try can be followed by many catch es –The first one that can catch the exception is the one that will catch the exception Bad: catch(Exception e) {... } catch(IOException e) {... } This is bad because IOException is a subclass of Exception, so any IOException will be handled by the first catch –The second catch phrase can never be used

Using the exception When you say catch(IOException e), e is a formal parameter of type IOException –So e is an instance of class IOException –It has methods you can use to examine it Here’s an especially useful method that is defined for every exception type: e.printStackTrace(); –This prints out what the exception was, and how you got to the statement that caused it

printStackTrace() printStackTrace() does not print on System.out, but on another stream, System.err From BlueJ: Look the DOS window that BlueJ opens to see the stack trace From the command line: both System.out and System.err are sent to the terminal window

Throwing an Exception If your method uses code that might throw an exception, and you don’t want to handle the exception in this method, you can say that the method “throws” the exception Example: String myGetLine( ) throws IOException {... } If you do this, then the method that calls this method must handle the exception

Constructing an Exception Exceptions are classes; you can create your own Exception with new –Most (all?) Exception types have two constructors: one with no parameters, and one with a String parameter You can subclass Exception to create your own exception type –But first, you should look through the predefined exceptions to see if there is already one that’s appropriate

Throwing an Exception Once you create an Exception, you can throw it –throw new UserException("Bad data"); You don’t have to throw an Exception ; here’s another thing you can do with one: –new UserException("Bad data").printStackTrace();

Why create an Exception? If you are writing methods for someone else to use, you want to do something reasonable if they use your methods incorrectly Just doing the wrong thing isn’t very friendly Remember, error messages are a good thing— much better than not having a clue what went wrong

The End