0% found this document useful (0 votes)
25 views34 pages

Week14 FL24 Exception Handling 2

Uploaded by

turkyalmuz90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views34 pages

Week14 FL24 Exception Handling 2

Uploaded by

turkyalmuz90
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

COMP2202

Fundamentals of Object Oriented


Programming
Chapter 10 – Exception Handling

1
Lecture Goals

 To throw and catch exceptions


 To implement programs that propagate checked exceptions

Copyright © 2014 by John Wiley & Sons. All rights


2
reserved.
Outline
 Throwing Exceptions
 Catching Exceptions
 Checked Exceptions
 The finally clause
 Designing Your Own Exception Types
 Application: Handling Input Errors

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 3
10.4 Exception Handling - Throwing Exceptions

 Exception handling provides a flexible mechanism for


passing control from the point of error detection to a
handler that can deal with the error.
 When you detect an error condition, throw an exception
object to signal an exceptional condition using the
throw statement
 If someone tries to withdraw too much money from a
bank account
• Throw an IllegalArgumentException
IllegalArgumentException exception =
new IllegalArgumentException("Amount exceeds balance");
throw exception;

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 4
Exception Handling - Throwing Exceptions
 When an exception is thrown, method terminates
immediately
• Execution continues with an exception handler
 When you throw an exception, the normal control flow
is terminated. This is similar to a circuit breaker that
cuts off the flow of electricity in a dangerous situation.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 5
Hierarchy of Exception Classes
Figure 2 A Part of the Hierarchy of Exception Classes

Copyright © 2014 by John Wiley & Sons. All rights reserved. 6


public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {class IllegalArgumentExceptionExample {
public
// Attempting
public static voidto divide by zero
main(String[] args) {
int {result = 10 / 0;
try
}public
catch (ArithmeticException
// Calling a method with e) an{illegal argument
class ClassCastExceptionExample {
System.out.println("Arithmetic
validateAge(-5);
public static void main(String[] Exception:
// This line will throw
args) " + e.getMessage());
{ IllegalArgumentException
} } catch
try {(IllegalArgumentException e) {
} System.out.println("Illegal Argument
// Attempting to cast a String to anException: " + e.getMessage());
Integer, which is not allowed
} } Object obj = "Hello, World!";
} Integer number = (Integer) obj; // This line will throw ClassCastException
} catch (ClassCastException e) {
public static void validateAge(int age)
System.out.println("Class Cast{Exception: " + e.getMessage());
if (age
} < 0) {
} throw new IllegalArgumentException("Age must be a non-negative value");
}}
// Continue processing if the age is valid
System.out.println("Valid Age: " + age);
}
}

Copyright © 2014 by John Wiley & Sons. All rights reserved. 7


public class ArrayIndexOutOfBoundsExceptionExample {
public static void main(String[] args) {
try {
// Attempting to access an array with an invalid index
public class NoSuchElementExceptionExample {
int[] numbers
public = {1, 2, 3};
publicclass
staticNullPointerExceptionExample
void main(String[] args) { {
int element = numbers[5]; // This line will throw
public
try { static void main(String[] args) {
//ArrayIndexOutOfBoundsException
try
// {Creating a Scanner with an empty input
} catch (ArrayIndexOutOfBoundsException e) {
Scanner scanner =tonew
// Attempting Scanner("");
invoke
System.out.println("Array IndexaOut
method on aException:
of Bounds null reference
" + e.getMessage());
} String str = null;
//int
Attempting
length = to read an element
str.length(); that
// This doesn't
line exist NullPointerException
will throw
}
double input = scanner.nextDouble(); // This line will throw
} } catch (NullPointerException e) {
NoSuchElementException
System.out.println("NullPointerException: " + e.getMessage());
} catch (NoSuchElementException e) {
} System.out.println("NoSuchElementException: " + e.getMessage());
}}
} }
}

Copyright © 2014 by John Wiley & Sons. All rights reserved. 8


public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
// Attempting to convert a non-numeric string to an integer
String nonNumericString = "abc";
int number = Integer.parseInt(nonNumericString); // This line will throw
//NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
}
}
}

Copyright © 2014 by John Wiley & Sons. All rights reserved. 9


InputMismatchException
InputMismatchException:
Scenario: This exception is typically thrown by methods such as nextInt(), nextDouble(),
etc., in the Scanner class when the input retrieved does not match the expected type.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 10


NoSuchElement

NoSuchElementException:

Scenario: This exception is thrown by methods like next(), nextInt(), etc., in the Scanner
class when there are no more elements to be retrieved.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 11


NumberFormat

NumberFormatException:

Scenario: This exception occurs when trying to convert a String to a numeric type
(e.g., int, double), but the String does not represent a valid number.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 12


ClassCastException

ClassCastException:

Scenario: This exception occurs when you try to cast an object to a type that it is not
an instance of. It is often associated with attempting to perform an inappropriate
type conversion at runtime.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 13


Syntax 10.1 Throwing an Exception

Copyright © 2014 by John Wiley & Sons. All rights reserved. 14


Catching Exceptions
 Every exception should be handled somewhere in your
program
 If an exception has no handler, an error message is printed,
and your program terminates.
 Place the statements that can cause an exception inside a
try block, and the handler inside a catch clause.
try
{
String filename = . . .;
Scanner in = new Scanner(new File(filename));
String input = in.next();
int value = Integer.parseInt(input);
...
}
catch (IOException exception)
{
exception.printStackTrace();
}
catch (NumberFormatException exception)
{
System.out.println(exception.getMessage());
} © 2014 by John Wiley & Sons. All rights
Copyright
reserved. 15
Catching Exceptions
 Three exceptions may be thrown in the try block:
• The Scanner constructor can throw a FileNotFoundException.
• Scanner.next can throw a NoSuchElementException.
• Integer.parseInt can throw a NumberFormatException.
 If any of these exceptions is actually thrown, then the
rest of the instructions in the try block are skipped.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 16
Catching Exceptions
 What happens when each exception is thrown:
• If a FileNotFoundException is thrown,
• then the catch clause for the IOException is executed because
FileNotFoundException is a descendant of IOException.
• If you want to show the user a different message for a
FileNotFoundException, you must place the catch clause before the
clause for an IOException
• If a NumberFormatException occurs,
• then the second catch clause is executed.
• A NoSuchElementException is not caught by any of the catch
clauses.
• The exception remains thrown until it is caught by another try
block.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 17
Syntax 10.2 Catching Exceptions

Copyright © 2014 by John Wiley & Sons. All rights reserved. 18


Catching Exceptions
 Each catch clause contains a handler.
 When the catch block is executed, then some method in
the try block has failed with exception.
 Our example just informed the user of a problem.
 Often better to give the user another chance to provide
correct input.
 When you throw an exception, you can provide your own
message string.
 For example, when you call
throw new IllegalArgumentException("Amount exceeds balance");
the message of the exception is the string provided in the
constructor.
 You should only catch those exceptions that you can
handle.
Copyright © 2014 by John Wiley & Sons. All rights
reserved. 19
Checked Exceptions
 Exceptions fall into three categories
• Internal errors are reported by descendants of the type Error.
• Example: OutOfMemoryError
• Descendants of RuntimeException,
• Example: IndexOutOfBoundsException or IllegalArgumentException
• Indicate errors in your code.
• They are called unchecked exceptions.
• All other exceptions are checked exceptions.
• Indicate that something has gone wrong for some external reason
beyond your control
• Example: IOException

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 20
Checked Exceptions
 Checked exceptions are due to external circumstances
that the programmer cannot prevent.
• Probably caused by forces beyond your control; such as a disk
error or no network connection.
• The compiler checks that your program handles these
exceptions.
 Unchecked exceptions are your fault.
• The compiler does not check whether you handle an unchecked
exception.
• For example; IndexOutOfBounds exception. Programmer should
check index values.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 21
Checked Exceptions - throws
 You can handle the checked exception in the same
method that throws it
try
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile); // ThrowsFileNotFoundException
...
}
catch (FileNotFoundException exception) // Exception caught here
{
...
}

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 22
Checked Exceptions - throws
 Often the current method cannot handle the exception.
Tell the compiler you are aware of the exception
 You want the method to terminate if the exception
occurs
 Add a throws clause to the method header
public void readData(String filename) throws FileNotFoundException
{
File inFile = new File(filename);
Scanner in = new Scanner(inFile);
...
}

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 23
Checked Exceptions - throws
 The throws clause signals to the caller of your method
that it may encounter a FileNotFoundException.
• The caller must decide
o To handle the exception
o Or declare the exception may be thrown
 Throw early, catch late
• Throw an exception as soon as a problem is detected.
• Catch it only when the problem can be handled
 Just as trucks with large or hazardous loads carry
warning signs, the throws clause warns the caller that
an exception may occur.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 24
Syntax 10.3 throws Clause

Some methods detect errors, some handle them, others just pass them along. The throws
clause ensures that no exceptions get lost along the way.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 25


The finally Clause
 Once a try block is entered, the statements in a finally
clause are guaranteed to be executed - whether or not
an exception is thrown.
 Use when you do some clean up
 Example - closing files
PrintWriter out = new PrintWriter(filename);
try
{
writeData(out);
}
finally
{
out.close();
}
 Executes the close even if an exception is thrown.

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 26
Syntax 10.4 finally Clause

the code in a finally clause is always executed,


even when an exception has occurred.

Copyright © 2014 by John Wiley & Sons. All rights reserved. 27


10.5 Application: Handling Input Errors
 Program asks user for the name of file
• File expected to contain data values
• First line of file contains total number of values
• Remaining lines contain the data
• Typical input file:
3
1.45
-2.1
0.05

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 28
Case Study: A Complete Example
 What can go wrong?
• File might not exist
• File might have data in the wrong format
 Who can detect the faults?
• Scanner constructor will throw an exception when file does not
exist
• Methods that process input need to throw exception if they find
error in data format
 What exceptions can be thrown?
• FileNotFoundException can be thrown by Scanner constructor
• BadDataException, a custom checked exception class for
reporting wrong data format

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 29
Case Study: A Complete Example
 Who can remedy the faults that the exceptions report?
• Only the main method of DataAnalyzer program interacts with
user
• Catches exceptions
• Prints appropriate error messages
• Gives user another chance to enter a correct file

Copyright © 2014 by John Wiley & Sons. All rights


reserved. 30
section_5/DataAnalyzer.java
1 import java.io.FileNotFoundException; //notice you need to import the exceptions packages
2 import java.io.IOException;
3 import java.util.Scanner;
4
5 /**
6 This program reads a file containing numbers and analyzes its contents.
7 If the file doesn&apos;t exist or contains strings that are not numbers, an
8 error message is displayed.
9 */
10 public class DataAnalyzer
11 {
12 public static void main(String[] args)
13 {
14 Scanner in = new Scanner(System.in);
15 DataSetReader reader = new DataSetReader();
16

Continued

Copyright © 2014 by John Wiley & Sons. All rights reserved. 31


section_5/DataAnalyzer.java
17 boolean done = false;
18 while (!done)
19 {
20 try
21 {
22 System.out.println("Please enter the file name: ");
23 String filename = in.next();
24
25 double[] data = reader.readFile(filename);
26 double sum = 0;
27 for (double d : data) { sum = sum + d; }
28 System.out.println("The sum is " + sum);
29 done = true;
30 }
31 catch (FileNotFoundException exception)
32 {
33 System.out.println("File not found.");
34 }
35 catch (BadDataException exception)
36 {
37 System.out.println("Bad data: " + exception.getMessage());
38 }
39 catch (IOException exception)
40 {
41 exception.printStackTrace();
42 }
43 }
44 }
45 }

Copyright © 2014 by John Wiley & Sons. All rights reserved. 32


Exercise: Add necessary try/catch exceptions
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class DivideFromFileExample {


public static void main(String[] args) throws FileNotFoundException {
// Opening the file
File file = new File("input.txt");

// Creating a Scanner to read from the file


Scanner fileScanner = new Scanner(file);

// Reading pairs of integers and performing division


while (fileScanner.hasNext()) {
int numerator = fileScanner.nextInt();
int divisor = fileScanner.nextInt();

// Performing division and printing the result


int result = performDivision(numerator, divisor);
System.out.println("Result of division: " + result);
Copyright ©}2014 by John Wiley & Sons. All rights reserved. 33
Continue code:
// Closing the file scanner
fileScanner.close();
}

private static int performDivision(int numerator, int divisor) {


if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return numerator / divisor;
}
}

Sample input file:

-2 3
60
82
1
a9
Copyright © 2014 by John Wiley & Sons. All rights reserved. 34

You might also like