Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Similar documents
Errors and Exceptions

Video 2.1. Arvind Bhusnurmath. Property of Penn Engineering, Arvind Bhusnurmath. SD1x-2 1

ECE 122. Engineering Problem Solving with Java

Exceptions - Example. Exceptions - Example

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exceptions. Examples of code which shows the syntax and all that

Exceptions. CSC207 Winter 2017

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Correctness and Robustness

Programming II (CS300)

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Data Structures. 02 Exception Handling

BBM 102 Introduction to Programming II Spring 2017

Sri Vidya College of Engineering & Technology Question Bank

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

Lecture 14: Exceptions 10:00 AM, Feb 26, 2018

Programming II (CS300)

Exceptions and Error Handling

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

CSCI 261 Computer Science II

CS159. Nathan Sprague

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

Main concepts to be covered. Handling errors. Some causes of error situations. Not always programmer error. Defensive programming.

COMP1008 Exceptions. Runtime Error

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

National University. Faculty of Computer Since and Technology Object Oriented Programming

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

6.Introducing Classes 9. Exceptions

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

CS 3 Introduction to Software Engineering. 3: Exceptions

14. Exception Handling

Exceptions. What exceptional things might our programs run in to?

Writing your own Exceptions. How to extend Exception

Java Programming Unit 7. Error Handling. Excep8ons.

Exceptions in Java

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Internal Classes and Exceptions

Programming Languages and Techniques (CIS120)

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Exceptions and Libraries

Comp 249 Programming Methodology Chapter 9 Exception Handling

Abstract Classes, Exceptions

Lab 2: File Input and Output

16-Dec-10. Consider the following method:

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

Program Correctness and Efficiency. Chapter 2

Introduction Unit 4: Input, output and exceptions

More on Exception Handling

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

More on Exception Handling

Java Exception. Wang Yang

Assertions and Exceptions Lecture 11 Fall 2005

Exceptions. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 15

Exceptions Handling Errors using Exceptions

EXCEPTION HANDLING. Summer 2018

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

17. Handling Runtime Problems

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

Object Oriented Programming. Week 7 Part 1 Exceptions

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

ITI Introduction to Computing II

School of Informatics, University of Edinburgh

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Exception Handling. Chapter 9

ITI Introduction to Computing II

Exception-Handling Overview

Full file at Chapter 2 - Inheritance and Exception Handling

CSE 331 Software Design & Implementation

CS193j, Stanford Handout #25. Exceptions

Exception Handling. Chapter 8. Chapter 8 1

Name: Checked: Preparation: Write the output of DeckOfCards.java to a text file Submit through Blackboard by 8:00am the morning of Lab.

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

Chapter 13 Exception Handling

Programming Languages and Techniques (CIS120)

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Transcription:

Errors and Exceptions 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 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 it isn t 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 s classes (or they use yours) You might use a class incorrectly Incorrect use should result in an exception 1

The problem with exceptions Here s s what you might like to do: open a file read a line from the file But here s 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 file, inform 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 It s s normal for human beings to be lazy Java tries to force you to handle exceptions This is sometimes a pain in the neck, but... the result is almost always a better program 2

Error and Exception are Objects 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 Exceptions s that are most important to us (since we have to do something about them) The Exception hierarchy II A few kinds of Exceptions Need not be caught Throwable Error Exception Must be caught RuntimeException 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 (this is a RuntimeException) NumberFormatException: : tried to convert a non- numeric String to a number (this is a RuntimeException) OutOfMemoryError: : the program has used all available memory (this is an Error) There are about 200 predefined Exception types! 3

What to do about Exceptions You have two choices: You can catch the exception and deal with it For Java s 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 exceptions that you create and throw 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, as in: void openfile(string filename) ) throws IOException {... } Which of these you do depends on whose responsibility it is to do something about the exception If the method knows what to do, it should do it If it should really be up to the user (the method caller) to decide what to do, then pass the buck 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 finally After all the catch phrases, you can have an optional finally phrase try {... } catch (AnExceptionType( e) {... } catch (AnotherExceptionType( e) {... } finally {... } Whatever happens in try and catch, even if it does a return statement, the finally code will be executed If no exception occurs, the finally will be executed after the try code In an exception does occur, the finally will be executed after the appropriate catch code 4

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 Whether or not an exception occurred, the finally code is executed Ordering the catch phrases A try can be followed by many catches 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 A catch phrase is almost like a miniature method e is an instance (object) of class IOException Exception objects have methods you can use Here s 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: : If it doesn t t show up in the output window, look in the DOS window that BlueJ opens From the command line: both System.out and System.err are sent to the terminal window printstacktrace(stream) prints on the given stream printstacktrace(system.out) prints on System.out,, and this output is printed along with the normal output 5

Throwing an Exception If your method uses code that might throw an exception, and you don t 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 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 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 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 t very friendly Remember, error messages are a good thing much better than not having a clue what went wrong Exceptions are even better than error messages, because they allow the user of your class to decide what to do 6

7