CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

Similar documents
Chapter 12 Exception Handling

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

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

BBM 102 Introduction to Programming II Spring Exceptions

Fundamentals of Object Oriented Programming

ITI Introduction to Computing II

Exception-Handling Overview

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

Programming II (CS300)

ITI Introduction to Computing II

Chapter 13 Exception Handling

Software Practice 1 - Error Handling

Programming II (CS300)

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

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

BBM 102 Introduction to Programming II Spring 2017

CS159. Nathan Sprague

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

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

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

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Data Structures. 02 Exception Handling

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

CMSC 202. Exceptions

CSCI 261 Computer Science II

C16b: Exception Handling

Exceptions and Error Handling

The Scanner class reads data entered by the user. Methods: COSC Dr. Ramon Lawrence. Page 3. COSC Dr. Ramon Lawrence A) A = 6, B = 3

Contents. I Introductory Examples. Topic 06 -Exception Handling

More on Exception Handling

Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5

Exceptions. CSC207 Winter 2017

More on Exception Handling

CS Programming I: Exceptions

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

CS 3 Introduction to Software Engineering. 3: Exceptions

Motivations. Chapter 12 Exceptions and File Input/Output

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

Exceptions - Example. Exceptions - Example

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

EXCEPTION HANDLING. Summer 2018

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

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

Input-Output and Exception Handling

CS159. Nathan Sprague

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

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

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

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

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

Intro to Computer Science II. Exceptions

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

Chapter 11 Handling Exceptions and Events. Chapter Objectives

COMP-202 Unit 9: Exceptions

CS Programming I: Exceptions

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

EXCEPTIONS. Fundamentals of Computer Science I

COMP1008 Exceptions. Runtime Error

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

ECE 122. Engineering Problem Solving with Java

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

What are Exceptions?

Computer Science is...

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

What can go wrong in a Java program while running?

Review. these are the instance variables. these are parameters to the methods

CSE115 Introduction to Computer Science I Coding Exercise #7 Retrospective Fall 2017

Objektorienterad programmering

Java Exception. Wang Yang

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

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

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

CSC 1214: Object-Oriented Programming

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

11/1/2011. Chapter Goals

Object Oriented Programming Exception Handling

Lecture 19 Programming Exceptions CSE11 Fall 2013

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

COMP-202 Unit 9: Exceptions

Java Errors and Exceptions. Because Murphy s Law never fails

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

Introductory Programming Exceptions and I/O: sections

6.Introducing Classes 9. Exceptions

Defensive Programming. Ric Glassey

16-Dec-10. Consider the following method:

Defensive Programming

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

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

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

Full file at Chapter 2 - Inheritance and Exception Handling

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

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

An exception is simply an error. Instead of saying an error occurred, we say that an.

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

Transcription:

CS1020 Data Structures and Algorithms I Lecture Note #8 Exceptions Handling exceptional events

Objectives Understand how to use the mechanism of exceptions to handle errors or exceptional events that occur during program execution 2

References Book Chapter 1, Section 1.6, pages 64 to 72 CS1020 website Resources Lectures http://www.comp.nus.edu.sg/ ~cs1020/2_resources/lectures.html 3

Outline 1. Motivation 2. Exception Indication 3. Exception Handling 4. Execution Flow 5. Checked vs Unchecked Exceptions 6. Defining New Exception Classes 4

1. Motivation (1/4) Three types of errors Syntax errors Occurs when the rule of the language is violated Detected by compiler Run-time errors Occurs when the computer detects an operation that cannot be carried out (eg: division by zero; x/y is syntactically correct, but if y is zero at run-time a runtime error will occur) Logic errors Easiest to detect and correct Hardest to detect and correct Occurs when a program does not perform the intended task 5

1. Motivation (2/4) import java.util.scanner; Example.java public class Example { public static void main(string[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter an integer: "); int num = sc.nextint(); If error occurs here System.out.println("num = " + num); The rest of the code is skipped and program is terminated. Enter an integer: abc Exception in thread "main" java.util.inputmismatchexception at java.util.scanner.throwfor(scanner.java:909) at java.util.scanner.next(scanner.java:1530) at java.util.scanner.nextint(scanner.java:2160) at java.util.scanner.nextint(scanner.java:2119) at Example1.main(Example1.java:8) 6

1. Motivation (3/4) Consider the factorial() method: What if the caller supplies a negative parameter? public static int factorial(int n) { int ans = 1; for (int i = 2; i <= n; i++) ans *= i; return ans; Should we terminate the program? public static int factorial(int n) { if (n < 0) { System.out.println("n is negative"); System.exit(1); //Other code not changed What if n is negative? System.exit(n) terminates the program with exit code n. In UNIX, you can check the exit code immediately after the program is terminated, with this command: echo $? Note that factorial() method can be used by other programs Hence, difficult to cater to all possible scenarios 7

1. Motivation (4/4) Instead of deciding how to deal with an error, Java provides the exception mechanism: 1. Indicate an error (exception event) has occurred 2. Let the user decide how to handle the problem in a separate section of code specific for that purpose 3. Crash the program if the error is not handled Exception mechanism consists of two components: Exception indication Exception handling Note that the preceding example of using exception for (n < 0) is solely illustrative. Exceptions are more appropriate for harder to check cases such as when the value of n is too big, causing overflow in computation. 8

SYNTAX 2. Exception Indication: Syntax (1/2) To indicate an error is detected: Also known as throwing an exception This allows the user to detect and handle the error throw ExceptionObject; Exception object must be: An object of a class derived from class Throwable Contain useful information about the error There are a number of useful predefined exception classes: ArithmeticException NullPointerException IndexOutOfBoundsException IllegalArgumentException 9

2. Exception Indication: Syntax (2/2) The different exception classes are used to categorize the type of error: There is no major difference in the available methods Constructor ExceptionClassName(String Msg) Construct an exception object with the error message Msg Common methods for Exception classes String void getmessage() Return the massage stored in the object printstacktrace() Print the calling stack 10

2. Exception Handling: Example #1 (1/2) import java.util.scanner; import java.util.inputmismatchexception; ExampleImproved.java public class ExampleImproved { public static void main(string[] args) { Scanner sc = new Scanner(System.in); boolean iserror = false; do { System.out.print("Enter an integer: "); try { int num = sc.nextint(); System.out.println("num = " + num); iserror = false; catch (InputMismatchException e) { System.out.print("Incorrect input: integer required. "); sc.nextline(); // skip newline iserror = true; while (iserror); 11

2. Exception Handling: Example #1 (2/2) do { System.out.print("Enter an integer: "); try { int num = sc.nextint(); System.out.println("num = " + num); iserror = false; catch (InputMismatchException e) { System.out.print("Incorrect input: integer required. "); sc.nextline(); // skip newline iserror = true; while (iserror); Enter an integer: abc Incorrect input: integer required. Enter an integer: def Incorrect input: integer required. Enter an integer: 1.23 Incorrect input: integer required. Enter an integer: 92 num = 92 12

2. Exception Indication: Example #2 public static int factorial(int n) throws IllegalArgumentException { if (n < 0) { IllegalArgumentException exobj = new IllegalArgumentException(n + " is invalid!"); throw exobj; int ans = 1; for (int i = 2; i <= n; i++) ans *= i; return ans; Note: This declares that method factorial() may throw IllegalArgumentException Actual act of throwing an exception (Note: throw and not throws ). These 2 statements can be shortened to: throw new IllegalArgumentException(n + " is invalid!"); A method can throw more than one type of exception 13

3. Exception Handling: Syntax As the user of a method that can throw exception(s): It is your responsibility to handle the exception(s) Also known as exception catching try { statement(s); catch (ExpClass1 obj1) { statement(s); catch (ExpClass2 obj2) { statement(s); finally { statement(s); // try block // exceptions might be thrown // followed by one or more catch block // a catch block // Do something about the exception // catch block for another type of exception // finally block for cleanup code 14

3. Exception Handling: Example public class TestException { public static int factorial(int n) throws IllegalArgumentException { //code not shown public static void main(string[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n: "); int input = sc.nextint(); try { System.out.println("Ans = " + factorial(input)); catch (IllegalArgumentException expobj) { System.out.println(expObj.getMessage()); We choose to print out the error message in this case. There are other ways to handle this error. See next slide for more complete code. 15

4. Execution Flow (1/2) public static int factorial(int n) throws IllegalArgumentException { System.out.println("Before Checking"); if (n < 0) { throw new IllegalArgumentException(n + " is invalid!"); System.out.println("After Checking"); //... other code not shown public static void main(string[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter n: "); int input = sc.nextint(); try { System.out.println("Before factorial()"); System.out.println("Ans = " + factorial(input)); System.out.println("After factorial()"); catch (IllegalArgumentException expobj) { System.out.println("In Catch Block"); System.out.println(expObj.getMessage()); finally { System.out.println("Finally!"); TestException.java Enter n: 4 Before factorial() Before Checking After Checking Ans = 24 After factorial() Finally! Enter n: -2 Before factorial() Before Checking In Catch Block -2 is invalid! Finally! 16

4. Execution Flow (2/2) public static void main(string[] args) { Scanner sc = new Scanner(System.in); int input; boolean retry = true; do { try { System.out.print("Enter n: "); input = sc.nextint(); Another version Keep retrying if n < 0 TestExceptionRetry.java Enter n: -2-2 is invalid! Enter n: -7-7 is invalid! Enter n: 6 Ans = 720 System.out.println("Ans = " + factorial(input)); retry = false; // no need to retry catch (IllegalArgumentException expobj) { System.out.println(expObj.getMessage()); while (retry); 17

5. Checked vs Unchecked Exceptions (1/2) Checked exceptions are those that require handling during compile time, or a compilation error will occur. Unchecked exceptions are those whose handling is not verified during compile time. RuntimeException, Error and their subclasses are unchecked exceptions. In general, unchecked exceptions are due to programming errors that are not recoverable, like accessing a null object (NullPointerException), accessing an array element outside the array bound (IndexOutOfBoundsException), etc. As unchecked exceptions can occur anywhere, and to avoid overuse of try-catch blocks, Java does not mandate that unchecked exceptions must be handled. 18

5. Checked vs Unchecked Exceptions (2/2) InputMismatchException and IllegalArgumentException are subclasses of RuntimeException, and hence they are unchecked exceptions. (Ref: ExampleImproved.java and TestException.java) 19

6. Defining New Exception Classes New exception classes can be defined by deriving from class Exception: public class MyException extends Exception { public MyException(String s) { super(s); The new exception class can then be used in throw statements and catch blocks: throw new MyException("MyException: Some reasons"); try {... catch (MyException e) {... 20

6. Example: Bank Account (1/5) public class NotEnoughFundException extends Exception { private double amount; public NotEnoughFundException(String s, double amount) { super(s); this.amount = amount; public double getamount() { return amount; NotEnoughFundException.java 21

6. Example: Bank Account (2/5) class BankAcct { BankAcct.java private int acctnum; private double balance; public BankAcct() { // By default, numeric attributes are initialised to 0 public BankAcct(int anum, double bal) { acctnum = anum; balance = bal; public int getacctnum() { return acctnum; public double getbalance() { return balance; 22

6. Example: Bank Account (3/5) public void deposit(double amount) { balance += amount; BankAcct.java public void withdraw(double amount) throws NotEnoughFundException { if (balance >= amount) { balance -= amount; else { double needs = amount - balance; throw new NotEnoughFundException( "Withdrawal Unsuccessful", needs); // class BankAcct 23

6. Example: Bank Account (4/5) public class TestBankAcct { TestBankAcct.java public static void main(string[] args) { BankAcct acc = new BankAcct(1234, 0.0); System.out.println("Current balance: $" + acc.getbalance()); System.out.println("Depositing $200..."); acc.deposit(200.0); System.out.println("Current balance: $" + acc.getbalance()); Current balance: $0.0 Depositing $200... Current balance: $200.0 24

6. Example: Bank Account (5/5) try { System.out.println("Withdrawing $150..."); acc.withdraw(150.0); System.out.println("Withdrawing $100..."); acc.withdraw(100.0); catch (NotEnoughFundException e) { System.out.println(e.getMessage()); System.out.println("Your account is short of $" + e.getamount()); finally { System.out.println("Current balance: $" + acc.getbalance()); // main // class TestBankAcct TestBankAcct.java Current balance: $0.0 Depositing $200... Current balance: $200.0 Withdrawing $150... Withdrawing $100... Withdrawal Unsuccessful Your account is short of $50.0 Current balance: $50.0 25

Practice Exercise Practice Exercises #24: Finding a Root of a Quadratic Equation #25: Making a Date 26

Summary We learned about exceptions, how to raise and handle them We learned how to define new exception classes 27

End of file