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

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

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

Programming II (CS300)

Programming II (CS300)

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

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

Object Oriented Programming Exception Handling

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

ECE 122. Engineering Problem Solving with Java

16-Dec-10. Consider the following method:

CS159. Nathan Sprague

BBM 102 Introduction to Programming II Spring Exceptions

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exception-Handling Overview

Exceptions in Java

CSCI 261 Computer Science II

COMP-202 Unit 9: Exceptions

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

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

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

Exceptions and Error Handling

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

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

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

Object Oriented Programming

CS159. Nathan Sprague

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

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

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

Exceptions - Example. Exceptions - Example

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

Std 12 Lesson-10 Exception Handling in Java ( 1

ITI Introduction to Computing II

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

COMP-202 Unit 9: Exceptions

BBM 102 Introduction to Programming II Spring 2017

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

C16b: Exception Handling

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

ITI Introduction to Computing II

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

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

Designing Robust Classes

Data Structures. 02 Exception Handling

Chapter 12 Exception Handling

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

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

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

CS112 Lecture: Exceptions and Assertions

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

6.Introducing Classes 9. Exceptions

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Fundamentals of Object Oriented Programming

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

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

Exceptions. CSC207 Winter 2017

CMSC 202. Exceptions

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

Exceptions and Libraries

Defensive Programming

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Exception Handling. Exception Handling

Errors and Exceptions

Checked and Unchecked Exceptions in Java

Java Errors and Exceptions. Because Murphy s Law never fails

Introduction to Java. Handout-3a. cs402 - Spring

Comp 249 Programming Methodology Chapter 9 Exception Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

CS 11 java track: lecture 3

Recitation 3. 2D Arrays, Exceptions

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

Defensive Programming. Ric Glassey

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

Exceptions and Design

Exception handling & logging Best Practices. Angelin

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

Chapter 13 Exception Handling

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

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

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

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

Introductory Programming Exceptions and I/O: sections

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

COMP1008 Exceptions. Runtime Error

Unit 4: Client View of a Component Methods

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

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Full file at Chapter 2 - Inheritance and Exception Handling

Chapter 11 Handling Exceptions and Events. Chapter Objectives

CS24: INTRODUCTION TO COMPUTING SYSTEMS. Spring 2018 Lecture 11

CSC 1214: Object-Oriented Programming

More on Exception Handling

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

Object Oriented Programming

More on Exception Handling

Transcription:

Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes when the computer tries to execute a statement something goes wrong: Trying to read a file that doesn t exist. Trying to divide an integer by zero. Calling a method with improper arguments. Say, calling the settime() method of a Clock object with arguments that does not refer to a valid hour. In these cases the instruction would fail. We say that a run-time error had occurred. 22 November 2007 Ariel Shamir 2 Methods Failure Calling a method can fail (wrong input parameters, calculation error, system call failure etc.) What should we do? Use a Boolean return value and write: if (myclock.settime(11,10,66) == true) { if (myclock.hourelapsed() == true) { if { 22 November 2007 Ariel Shamir 3 1

Problems in This Approach? Not possible to return a value other than Boolean Difficult to understand the code No indication what exactly went wrong 22 November 2007 Ariel Shamir 4 Exceptions In Java, run-time errors are indicated by exceptions. If a method wants to signal that something went wrong during its execution it throws an exception. 22 November 2007 Ariel Shamir 5 Throwing an Exception Throwing an exception involves: creating an exception object that encloses information about the problem that occurred use of the statement throw to notify about the exception Throw Object 22 November 2007 Ariel Shamir 6 2

Throwing an Exception Example public void settime( int hour, int minute, int second) { if (hour<0 hour>23 minute<0 minute>59 second<0 second>59) { throw new IllegalArgumentException( Invalid time ); this.hour = hour; this.minute = minute; this.second = second; 22 November 2007 Ariel Shamir 7 The Exception Object The information about the problem that occurred is enclosed in a real object, the exception object. This information includes: The type of the problem The place in the code where the exception occurred The state of the run-time stack... other information 22 November 2007 Ariel Shamir 8 Who Receives the Exception? The code that invoked the method will receive the exception object. Clock myclock = new Clock(); myclock.settime(11,10,66); Call Exception It can then examine the information it carries and act accordingly (later). settime Method 22 November 2007 Ariel Shamir 9 3

The Type of the Exception The most important information is the type of the exception This is indicated by the class (i.e. type) of the exception object The Java API defines classes for many types of exceptions You can define more of your own 22 November 2007 Ariel Shamir 10 Illegal Argument Exception The settime() method used the exception IllegalArgumentException to signal that the values of the arguments were not valid. IllegalArgumentException is a class defined in package java.lang. A method throws this type of exception if it wants to signal that an argument it got is not legal. 22 November 2007 Ariel Shamir 11 Examples of Exception Types Several types of exceptions are defined in java.lang: IllegalArgumentException - passing an illegal argument to a method. Example: Math.pow(0,0); ArithmeticException - division by zero. NullPointerException - trying to refer to an object through a reference variable whose value is null. 22 November 2007 Ariel Shamir 12 4

Occurrence of an Exception When a program performs an illegal operation the following happens: An exception object is created and thrown The regular flow of the program stops The program may try to handle the exceptional situation (in a way we will explain shortly) If the program ignores the exception the program execution ceases. We sometimes say that the program crashes. 22 November 2007 Ariel Shamir 13 Occurrence of an Exception Example class ClockProblem { public static void main(string[] args) { int hours,minuets,seconds; Clock myclock = new Clock(); myclock.settime(hours,minuets,seconds); What happens if hours<0 or seconds>59? 22 November 2007 Ariel Shamir 14 The Root of the Exception public void settime( int hour, int minute, int second) { if (hour<0 hour>23 minute<0 minute>59 second<0 second>59) { throw new IllegalArgumentException( Invalid time ); this.hour = hour; this.minute = minute; this.second = second; 22 November 2007 Ariel Shamir 15 5

Exception Outcome class ClockProblem { public static void main(string[] args) { A Clock must int hours = -1; int minuets,seconds; hour = -1 have a positive hour Hey, no one cares to Clock myclock = new Clock(); listen! myclock.settime(hours,minuets,seconds); I ll crash the method! 22 November 2007 Ariel Shamir 16 Avoiding Exceptions In the former example we could have checked if the parameters are legal. Sometimes we cannot prevent an exceptional state. For example when reading from a diskette we cannot tell if the diskette is readable or not without trying to read from it. 22 November 2007 Ariel Shamir 17 Separating Exception Cases in Your Code Even if we can check in advance if there is a possibility of running into an exceptional case we may want to handle this case outside the main block, so as not to complicate the readability of the handling of the regular case. 22 November 2007 Ariel Shamir 18 6

Handling Exceptions In order to handle exceptional cases, you should put the code section that might throw an exception inside the body of a try..catch statement. The parenthesis that follow the catch keyword, specify the type of exception we want to handle. 22 November 2007 Ariel Shamir 19 Try.. Catch Block The idea is to "try" and execute some statements. If whatever you tried succeeds, the catch statements are ignored. If an exception is thrown by any of the statements within the try block, the rest of the statements are skipped and the corresponding catch block is executed. 22 November 2007 Ariel Shamir 20 Try..Catch Syntax try { // code statements catch (ExceptionType e) { // handler statements Each catch clause has an associated exception type. When an exception occurs, processing continues at the first catch clause that matches the exception type. 22 November 2007 Ariel Shamir 21 7

Handling Exceptions Example class ClockProblem { public static void main(string[] args) { int hour, minuets,seconds; Clock myclock = new Clock(); try { myclock.settime(hours,minuets,seconds); catch (IllegalArgumentException iae) { // act accordingly... Call settime Method Exception 22 November 2007 Ariel Shamir 22 Handling Other Exceptions class ClockProblem { public static void main(string[] args) { Clock myclock = new Clock(); try { myclock.settime(hours,minuets,seconds); catch (ArithmeticException ae) { catch (IllegalArgumentException ia) { output.println( Illegal input! ); 22 November 2007 Ariel Shamir 23 Declaring for Exceptions A method can declare exceptions it may throw. We will see later that sometimes this is a must The declaration for exceptions a method can throw is done using the throws keyword The user of the method is warned against possible exceptions this method can throw 22 November 2007 Ariel Shamir 24 8

Declaring Exceptions Using throws public void settime( int hour, int minute, int second) throws IllegalArgumentException { if (hour<0 hour>23 minute<0 minute>59 second<0 second>59) { throw new IllegalArgumentException( Invalid time ); this.hour = hour; 22 November 2007 Ariel Shamir 25 Documenting Exceptions The exceptions that might be thrown by a method should also be documented with the @exception tag or @throws : /** * Sets the time of the clock. * @param hour, minute, second The new time. * @throws IllegalArgumentException If the * parameters don t represent a valid time. */ 22 November 2007 Ariel Shamir 26 Exception Hierarchy 22 November 2007 Ariel Shamir 27 9

RuntimeException Every exception is a runtime error. Exceptions of type RuntimeException do not have to be declared. A routine can throw an IllegalArgumentException without announcing the possibility. A program that calls that routine is free either to catch or to ignore such exception. 22 November 2007 Ariel Shamir 28 Mandatory Declaration For those exception classes that require mandatory handling, the situation is different. If a subroutine can throw such an exception, that fact must be announced in a throws clause in the routine definition. Failing to do so is a syntax error that will be reported by the compiler. 22 November 2007 Ariel Shamir 29 Mandatory Handling The calling method must either catch the mandatory exception or declare that it can throw it using the throws clause. This is because if this exception is not caught, it will be delegated to the next level of method call. 22 November 2007 Ariel Shamir 30 10

Creating Your Own Exception public class EmpNotFoundException extends Exception { public EmpNotFoundException(String name) { super("employee " + name + " is not found in comapny"); 22 November 2007 Ariel Shamir 31 Throwing Your Exception public class CompanyE { private String[] names; // more... public void pay(string employeename) throws EmpNotFoundException { int index = lookfor(employeename); if (index == -1) throw new EmpNotFoundException(employeeName); Employee e = getemployee(index); e.pay(); 22 November 2007 Ariel Shamir 32 Finally Block try { // statements (may include return)... // Executed normally catch (Exception e) { // statements... // Executed when exceptions are thrown finally { // statements... // Executed after all catch cases // Also after the try statements // Even before (if it includes a return) // we exit from the method! 22 November 2007 Ariel Shamir 33 11

Advantages of Exceptions Reduces programming complexity ( clean code ) Prevents ignoring errors Refers errors to where they can be dealt with Frees the method return value mechanism Provides more informative than just a return value 22 November 2007 Ariel Shamir 34 12