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

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
COMP 121 Week 5: Exceptions and Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
CS1101: Programming Methodology Aaron Tan.
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
COMP Exception Handling Yi Hong June 10, 2015.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 10 – Exception Handling
Chapter 13 Exception Handling
Chapter 15 – Exception Handling
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Fundamental Error Handling
Chapter 13 Exception Handling
Lecture 11 Objectives Learn what an exception is.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Chapter 12 Exception Handling and Text IO Part 1
Java Programming: From Problem Analysis to Program Design, 4e
Throwing, Catching Defining
Presentation transcript:

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

Objectives 2 [CS1020 Lecture 6: Exceptions] Understand how to use the mechanism of exceptions to handle errors or exceptional events that occur during program execution

References 3 Book Chapter 1, Section 1.6, pages 64 to 72 CS1020 website  Resources  Lectures ~cs1020/2_resources/lectures.htmlhttp:// ~cs1020/2_resources/lectures.html [CS1020 Lecture 6: Exceptions]

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

1. Motivation (1/4) 5 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 run- time error will occur) Logic errors  Occurs when a program does not perform the intended task [CS1020 Lecture 6: Exceptions] Easiest to detect and correct Hardest to detect and correct

1. Motivation (2/4) 6 import java.util.Scanner; 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(); System.out.println("num = " + num); } [CS1020 Lecture 6: Exceptions] Example.java 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)  If error occurs here  The rest of the code is skipped and program is terminated.

1. Motivation (3/4) 7 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; } What if n is negative? 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 } 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 [CS1020 Lecture 6: Exceptions]

1. Motivation (4/4) 8 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. [CS1020 Lecture 6: Exceptions]

2. Exception Indication: Syntax (1/2) 9 To indicate an error is detected:  Also known as throwing an exception  This allows the user to detect and handle the error throw ExceptionObject; SYNTAX 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 [CS1020 Lecture 6: Exceptions]

2. Exception Indication: Syntax (2/2) 10 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 StringgetMessage() Return the massage stored in the object voidprintStackTrace() Print the calling stack [CS1020 Lecture 6: Exceptions]

2. Exception Handling: Example #1 (1/2) 11 [CS1020 Lecture 6: Exceptions] import java.util.Scanner; import java.util.InputMismatchException; 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); } ExampleImproved.java

2. Exception Handling: Example #1 (2/2) 12 [CS1020 Lecture 6: Exceptions] 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

2. Exception Indication: Example 13 Note:  A method can throw more than one type of exception 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; } 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!"); [CS1020 Lecture 6: Exceptions]

3. Exception Handling: Syntax 14 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 [CS1020 Lecture 6: Exceptions]

3. Exception Handling: Example 15 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. [CS1020 Lecture 6: Exceptions]

4. Execution Flow (1/2) 16 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!"); } public static int factorial(int n) throws IllegalArgumentException { System.out.println("Before Checking"); if (n < 0) { throw new IllegalArgumentException(...); } System.out.println("After Checking"); //... other code not shown } 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! TestException.java [CS1020 Lecture 6: Exceptions]

4. Execution Flow (2/2) 17 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(); System.out.println("Ans = " + factorial(input)); retry = false; // no need to retry } catch (IllegalArgumentException expObj) { System.out.println(expObj.getMessage()); } } while (retry); } Enter n: is invalid! Enter n: is invalid! Enter n: 6 Ans = 720 TestExceptionRetry.java [CS1020 Lecture 6: Exceptions] Another version  Keep retrying if n < 0

5. Checked vs Unchecked Exceptions (1/2) 18 [CS1020 Lecture 6: Exceptions] 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.

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

5. Defining New Exception Classes 20 [CS1020 Lecture 6: Exceptions] 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: try {... } catch (MyException e) {... } throw new MyException("MyException: Some reasons");

5. Example: Bank Account (1/5) 21 public class NotEnoughFundException extends Exception { private double amount; public NotEnoughFundException(String s, double amount) { super(s); this.amount = amount; } public double getAmount() { return amount; } [CS1020 Lecture 6: Exceptions] NotEnoughFundException.java

5. Example: Bank Account (2/5) 22 class BankAcct { 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; } [CS1020 Lecture 6: Exceptions] BankAcct.java

5. Example: Bank Account (3/5) 23 public void deposit(double amount) { balance += amount; } 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 [CS1020 Lecture 6: Exceptions] BankAcct.java

5. Example: Bank Account (4/5) 24 public class TestBankAcct { 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()); [CS1020 Lecture 6: Exceptions] TestBankAcct.java Current balance: $0.0 Depositing $ Current balance: $200.0

5. Example: Bank Account (5/5) 25 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 [CS1020 Lecture 6: Exceptions] TestBankAcct.java Current balance: $0.0 Depositing $ Current balance: $200.0 Withdrawing $ Withdrawing $ Withdrawal Unsuccessful Your account is short of $50.0 Current balance: $50.0

Summary 26 We learned about exceptions, how to raise and handle them We learned how to define new exception classes [CS1020 Lecture 6: Exceptions]

End of file