Exceptions, Lecture notes of Data Structures and Algorithms

Example.java. Enter an integer: abc. Exception in thread main java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909).

Typology: Lecture notes

2022/2023

Uploaded on 03/01/2023

thecoral
thecoral 🇺🇸

4.5

(30)

395 documents

1 / 28

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
CS1020 Data Structures and Algorithms I
Lecture Note #8
Exceptions
Handling exceptional events
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c

Partial preview of the text

Download Exceptions and more Lecture notes Data Structures and Algorithms in PDF only on Docsity!

CS1020 Data Structures and Algorithms I

Lecture Note

Exceptions

Handling exceptional events

Objectives

[CS1020 Lecture 8 : Exceptions]

 Understand how to use the mechanism of

exceptions to handle errors or exceptional

events that occur during program execution

Outline

  1. Motivation
  2. Exception Indication
  3. Exception Handling
  4. Execution Flow
  5. Checked vs Unchecked Exceptions
  6. Defining New Exception Classes [CS1020 Lecture 8 : Exceptions]
  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 run- time error will occur)

 Logic errors

 Occurs when a program does not perform the intended task

Easiest to detect and correct
Hardest to detect and correct

[CS1020 Lecture 8 : Exceptions]

  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; }

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 8 : Exceptions]

  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. [CS1020 Lecture 8 : Exceptions]

  1. 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 getMessage()
Return the massage stored in the object
void printStackTrace()
Print the calling stack

[CS1020 Lecture 8 : Exceptions]

[CS1020 Lecture 8 : Exceptions]

  1. Exception Handling: Example #1 (1/2) 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
  1. Exception Indication: Example #  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 8 : Exceptions]

  1. 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

[CS1020 Lecture 8 : Exceptions]

  1. Execution Flow (1/2) 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(n + " is invalid!"); } 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 8 : Exceptions]
  1. 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(); System.out.println("Ans = " + factorial(input)); retry = false; // no need to retry } catch (IllegalArgumentException expObj) { System.out.println(expObj.getMessage()); } } while (retry); } Enter n: - 2
  • 2 is invalid! Enter n: - 7
  • 7 is invalid! Enter n: 6 Ans = 720 TestExceptionRetry.java

 Another version

 Keep retrying if n < 0 [CS1020 Lecture 8 : Exceptions]

  1. 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) [CS1020 Lecture 8 : Exceptions]
  1. 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:

try {
} catch (MyException e) {
throw new MyException("MyException: Some reasons");

[CS1020 Lecture 8 : Exceptions]