Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Similar documents
Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Exceptions - Example. Exceptions - Example

More on Exception Handling

CS159. Nathan Sprague

More on Exception Handling

Internal Classes and Exceptions

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions Handling Errors using Exceptions

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

Programming Languages and Techniques (CIS120)

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

Full file at Chapter 2 - Inheritance and Exception Handling

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

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

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

School of Informatics, University of Edinburgh

Exception-Handling Overview

BBM 102 Introduction to Programming II Spring 2017

COMP1008 Exceptions. Runtime Error

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

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

CS159. Nathan Sprague

Download link: Java Exception Handling

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

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

Data Structures. 02 Exception Handling

Lecture 19 Programming Exceptions CSE11 Fall 2013

Recreation. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

16-Dec-10. Consider the following method:

Errors and Exceptions

CS61B Lecture #12. Today: Various odds and ends in support of abstraction.

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

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

ITI Introduction to Computing II

EXCEPTIONS. Java Programming

For more details on SUN Certifications, visit

CS 61B Discussion 5: Inheritance II Fall 2014

ITI Introduction to Computing II

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

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

CSCI 261 Computer Science II

Fundamentals of Object Oriented Programming

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

EXCEPTIONS. Prof. Chris Jermaine

What can go wrong in a Java program while running?

Exceptions and Libraries

CS 3 Introduction to Software Engineering. 3: Exceptions

Sri Vidya College of Engineering & Technology Question Bank

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

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Programming Languages and Techniques (CIS120e)

ECE 122. Engineering Problem Solving with Java

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

Exception Handling. Chapter 9

Checked and Unchecked Exceptions in Java

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

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

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

CS1092: Tutorial Sheet: No 3 Exceptions and Files. Tutor s Guide

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

Defensive Programming. Ric Glassey

Assertions and Exceptions Lecture 11 Fall 2005

CSE 143 Java. Exceptions 1/25/

COS226 - Spring 2018 Class Meeting # 21 April 23, 2018

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

Typecasts and Dynamic Dispatch. Dynamic dispatch

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

CSE 331 Software Design & Implementation

What are Exceptions?

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

Introductory Programming Exceptions and I/O: sections

CS112 Lecture: Exceptions and Assertions

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

17. Handling Runtime Problems

PIC 20A Exceptions. Ernest Ryu UCLA Mathematics. Last edited: November 27, 2017

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

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

EXCEPTION HANDLING. Summer 2018

Introduction Unit 4: Input, output and exceptions

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

Program Correctness and Efficiency. Chapter 2

EXCEPTIONS. Fundamentals of Computer Science I

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

SECTION-1 Q.1.Which two code fragments are most likely to cause a StackOverflowError? (Choose two.)

Input-Output and Exception Handling

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

Here is a hierarchy of classes to deal with Input and Output streams.

Programming II (CS300)

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

6.Introducing Classes 9. Exceptions

Data Structure. Recitation IV

Java Programming Unit 7. Error Handling. Excep8ons.

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

Java in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.

Programming Languages and Techniques (CIS120)

Introduction to Java Written by John Bell for CS 342, Spring 2018

Principles of Software Construction: Objects, Design, and Concurrency. Objects (continued) toad. Spring J Aldrich and W Scherlis

C16b: Exception Handling

Transcription:

Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions. You will also be able to describe the class model for exceptions in Java. You will also be able to create, throw and catch your own exceptions. 1 2 What s the worst/funniest error message you ve seen on your computer? 3 4 1

Error Codes How have you handled errors in your programs so far? Did you run into any difficulties using atof? what happens when you enter 0? what happens when you enter hello? strtod: sets the value of a global variable called errno to something other than 0 (depending on the type of error). 5 6 Reporting Errors (GNOME) If you considered all of the possible stuff someone could type into your program and handled it nicely, what would the code look like in C? GNOME Human Interface Guidelines 2.2 11.2 Warning and Error Messages: A good warning or error message contains two elements: 1. A brief description of the problem. 2. A list of ways the user can remedy the problem. Both of these elements should be presented in nontechnical, jargon-free language, unless your target audience is particularly technically-minded. 7 8 2

Reporting Errors (Vista) Windows User Experience Interaction Guidelines (Windows Vista) Effective error messages inform users that a problem occurred, explain why it happened, and provide a solution so users can fix the problem. Reporting Errors (Apple) Apple Human Interface Guidelines Provide useful error messages to users when something does go wrong. An error message should clearly convey what happened, why it happened, and the options for proceeding. 9 10 Dealing with Errors Possibilities 1 2 3 Where would you put the code to handle the error? Error Handled in 3: Advantage: know specific reason for error Disadvantage: don t know context Handled in 1: Advantage: know about context Disadvantage: need code added to s 1 & 2 to pass back info about reason for error 11 12 3

Exceptions Throwing an Exception Basic idea: Program flows according to usual constructs (sequential, conditional, iterative execution, etc.) Something exceptional happens Interrupt normal behaviour by throwing an exception (an object with error information) Somewhere (anywhere) up the call stack, this exception can be caught and handled Transfer control to the catching method (removing everything below it from the call stack) 1 2 3 Error 13 14 Java Exception Handling Keywords catch finally throw throws Catching an Exception //... some code which might throw an exception catch (Exception x) //... code which handles the exception finally //... code which is executed no matter what 15 16 4

Example Example import java.util.arraylist; import java.util.arraylist; public class ExceptionExample ArrayList<String> strs = new ArrayList<String>(); String s = strs.get(100); System.out.println(s); What will happen? 17 public class ExceptionExample ArrayList<String> strs = new ArrayList<String>(); String s = strs.get(100); System.out.println(s); catch (Exception x) System.err.println("An error occured"); System.err.println(x.getMessage()); x.printstacktrace(system.err); 18 Exceptions are Objects Example: Out of Bounds import java.util.arraylist; Throwable Exception 19 public class ExceptionExample ArrayList<String> strs = new ArrayList<String>(); String s = strs.get(100); System.out.println(s); catch (ArrayIndexOutOfBoundsException x) System.err.println("An error occured"); System.err.println(x.getMessage()); x.printstacktrace(system.err); 20 5

Example: Parsing Integers Errors vs. Exceptions public class Number int count = 0; Throwable while(count < args.length) int x = Integer.parseInt(args[count]); System.out.println("Args[" + count + "] = " + x); catch(numberformatexception x) System.err.println("Invalid parameter:" + count); System.err.println(x.getMessage()); System.err.println("Stack trace:"); x.printstacktrace(system.err); count++; Error Exception 21 22 Errors vs. Exceptions Errors Something the programmer should not reasonably be expected to recover from. Exceptions Something the programmer should reasonably be expected to recover from Exercise: Error or Exception Read data outside array boundary Heap is full (out of memory) Null pointer File does not exist Hard disk failure 23 24 6

Catching Multiple Exceptions //... some code which might throw an exception catch (ExceptionOne x) //... code which handles ExceptionOne's catch (ExceptionTwo x) //... code which handles ExceptionTwo's import java.io.*; public class FileExample FileReader reader = new FileReader(args[0]); int c = reader.read(); reader.close(); catch (ArrayIndexOutOfBoundsException e) System.err("Must specify an argument"); catch (FileNotFoundException e) System.err("File not found: " + args[0]); catch (IOException e) System.err("Error reading file: " + args[0]); e.printstacktrace(); 25 26 Checked vs. Unchecked Exceptions Checked vs. Unchecked Exceptions Exception RuntimeException Checked Subclasses of Exception that do not inherit from RuntimeException Compiler will complain if uncaught Unchecked Subclasses of RuntimeException Can be ignored by the programmer 27 28 7

Exercise Lookup ClassCastException in Java API Is it checked or unchecked? Creating Exceptions public class DriverMismatchException extends Exception public DriverMismatchException(String message) super(message); 29 30 Throwing Exceptions Creating & Throwing Exceptions public class Driver private Car car; public Driver(Car car) throws DriverMismatchException if (car.getdriver()!= this) throw new DriverMismatchException( "Car does not match driver"); this.car = car; Creating Exceptions Inherit from Exception Can inherit from subclass of Exception e.g., IllegalArgumentException, RuntimeException Throwing Exceptions Use throw command If checked, requires a throws declaration 31 32 8

Example: Constructors Has no return value If an invalid state is reached, exceptions are a nice way to handle the error Is there another way? Exercise Look up one of each of the following: an Error an unchecked Exception a checked Exception Draw the class model starting at the Throwable class. 33 34 Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions...catch...finally throw and throws Next Class Collections 35 36 9