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

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

Exceptions - Example. Exceptions - Example

More on Exception Handling

More on Exception Handling

Exceptions Handling Errors using Exceptions

CS159. Nathan Sprague

BBM 102 Introduction to Programming II Spring Exceptions

Full file at Chapter 2 - Inheritance and Exception Handling

Programming Languages and Techniques (CIS120)

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

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

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

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

Exception-Handling Overview

School of Informatics, University of Edinburgh

Internal Classes and Exceptions

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

16-Dec-10. Consider the following method:

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

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

COMP1008 Exceptions. Runtime Error

BBM 102 Introduction to Programming II Spring 2017

CS159. Nathan Sprague

Lecture 19 Programming Exceptions CSE11 Fall 2013

CS 61B Discussion 5: Inheritance II Fall 2014

Fundamentals of Object Oriented Programming

For more details on SUN Certifications, visit

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

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

Errors and Exceptions

Data Structures. 02 Exception Handling

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

COMP 401 EXCEPTIONS. Instructor: Prasun Dewan

CSCI 261 Computer Science II

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

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

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

Programming Languages and Techniques (CIS120e)

Checked and Unchecked Exceptions in Java

Exceptions and Libraries

EXCEPTIONS. Java Programming

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

Download link: Java Exception Handling

ITI Introduction to Computing II

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

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

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

ITI Introduction to Computing II

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

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

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

What can go wrong in a Java program while running?

COMP-202 Unit 9: Exceptions

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

EXCEPTIONS. Prof. Chris Jermaine

Sri Vidya College of Engineering & Technology Question Bank

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

Introductory Programming Exceptions and I/O: sections

Typecasts and Dynamic Dispatch. Dynamic dispatch

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

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

What are Exceptions?

EXCEPTIONS. Fundamentals of Computer Science I

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

Exceptions and Error Handling

COE318 Lecture Notes Week 10 (Nov 7, 2011)

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

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

Input-Output and Exception Handling

Writing your own Exceptions. How to extend Exception

C16b: Exception Handling

Defensive Programming. Ric Glassey

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

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

CSE 143 Java. Exceptions 1/25/

Programming II (CS300)

Java Programming Unit 7. Error Handling. Excep8ons.

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

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Assertions and Exceptions Lecture 11 Fall 2005

Programming Languages and Techniques (CIS120)

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

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

ECE 122. Engineering Problem Solving with Java

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

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

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

EXCEPTION HANDLING. Summer 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception Handling. Chapter 9

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

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

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

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

CSE 331 Software Design & Implementation

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

Program Correctness and Efficiency. Chapter 2

Transcription:

Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 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. 2 1

What s the worst/funniest error message you ve seen on your computer? 3 4 2

How have you handled errors in your programs so far? 5 Error Codes 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). 6 3

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? 7 Reporting Errors (GNOME) 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. 8 4

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. 9 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. 10 5

Dealing with Errors Function 1 Function 2 Function 3 Error Where would you put the code to handle the error? 11 Possibilities Handled in Function 3: Advantage: know specific reason for error Disadvantage: don t know context Handled in Function 1: Advantage: know about context Disadvantage: need code added to Functions 1 & 2 to pass back info about reason for error 12 6

Exceptions 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) 13 Throwing an Exception Function 1 Function 2 Function 3 Error 14 7

Java Exception Handling Keywords try catch finally throw throws 15 Catching an Exception try //... some code which might throw an exception catch (Exception x) //... code which handles the exception finally //... code which is executed no matter what 16 8

Example import java.util.arraylist; public class ExceptionExample public static void main(string[] args) ArrayList<String> strs = new ArrayList<String>(); String s = strs.get(100); System.out.println(s); What will happen? 17 Example import java.util.arraylist; public class ExceptionExample public static void main(string[] args) try 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 9

Exceptions are Objects Throwable Exception 19 Example: Out of Bounds import java.util.arraylist; public class ExceptionExample public static void main(string[] args) try 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 10

Example: Parsing Integers public class Number public static void main(string[] args) int count = 0; while(count < args.length) try 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++; 21 Errors vs. Exceptions Throwable Error Exception 22 11

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 23 Exercise: Error or Exception Read data outside array boundary Heap is full (out of memory) Null pointer File does not exist Hard disk failure 24 12

Catching Multiple Exceptions try //... some code which might throw an exception catch (ExceptionOne x) //... code which handles ExceptionOne's catch (ExceptionTwo x) //... code which handles ExceptionTwo's 25 import java.io.*; public class FileExample public static void main(string[] args) try 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(); 26 13

Checked vs. Unchecked Exceptions Exception RuntimeException 27 Checked vs. Unchecked Exceptions 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 28 14

Exercise Lookup ClassCastException in Java API Is it checked or unchecked? 29 Creating Exceptions public class DriverMismatchException extends Exception public DriverMismatchException(String message) super(message); 30 15

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; 31 Creating & Throwing Exceptions 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 32 16

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? 33 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. 34 17

Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 35 Next Class Collections 36 18