0% found this document useful (0 votes)
40 views

Chapter 7 Exceptions

This document discusses exceptions in Java programs. It begins by explaining that programs can encounter problems like negative array indexes or illegal user input. It then introduces the Error and Exception classes in Java that deal with such problems. The rest of the document discusses exception handling using try/catch blocks to recover from exceptions and provides an example program that prompts the user for input and catches an InputMismatchException if non-integer data is entered.

Uploaded by

Johncena25052504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Chapter 7 Exceptions

This document discusses exceptions in Java programs. It begins by explaining that programs can encounter problems like negative array indexes or illegal user input. It then introduces the Error and Exception classes in Java that deal with such problems. The rest of the document discusses exception handling using try/catch blocks to recover from exceptions and provides an example program that prompts the user for input and catches an InputMismatchException if non-integer data is entered.

Uploaded by

Johncena25052504
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

M.

El Dick 1

Introduction
2

A program often encounters problems as it executes


 Examples: negative array index, illegal input from user

 Java classes Error and Exception deal with such


problems

Recover from errors and keep on running

EXCEPTIONS
Chapter 7 M. El Dick

What went wrong? Throwable Hierarchy


12-3 4

Running some class Square :  Any Java method can “throw” an Object
object of class Throwable
Enter an integer: rats
Exception in thread "main" java.util.InputMismatchException  Programs can recover from Throwable
at java.util.Scanner.throwFor(Unknown Source) Exceptions
at java.util.Scanner.next(Unknown Source)  Can “catch” Exceptions
extend
at java.util.Scanner.nextInt(Unknown Source) Exception Error
 Programs cannot recover from
at java.util.Scanner.nextInt(Unknown Source)
Errors
at Square.main(Square.java:12)

M. El Dick M. El Dick
Object

Throwable
InputMismatchException
6

import java.util.* ; nextInt() threw the Exception


Exception public class Square
{
public static void main ( String[] a ) No code to deal with this Exception
{
InterruptedException IOException RunTimeException ParseException Others … Scanner scan = new Scanner( System.in );
int num ;
System.out.print("Enter an integer: ");
num = scan.nextInt();
System.out.println("The square of " + num + " is " +
IndexOutOfBoundsException NoSuchElementException NullPointerException ArithmeticException num*num );
}
} JVM caught this Exception and
stopped program
InputMismatchException
5 M. El Dick M. El Dick

import java.util.* ;
public class Square

try{} and catch{} {


public static void main ( String[] a )
7
{
 To catch an Exception: Scanner scan = new Scanner( System.in );
int num ;
 Put code that might throw an Exception inside a try{} System.out.print("Enter an integer: ");
block try
 Put code that handles the Exception inside a catch{} {
block num = scan.nextInt();
System.out.println("The square of " + num + " is " + num*num );
}
catch ( InputMismatchException ex )
{
System.out.println("You entered bad data." );
System.out.println("Run the program again." );
}
System.out.println("Goodbye" );
M. El Dick 8 }} M. El Dick
public class SquareUser
Exercise {public static void main ( String[] a ) {
Scanner scan = new Scanner( System.in );
9
int num = 0 ;
boolean goodData = false; If the user enters 34.56, would
 Modify the previous program so that the user is while ( !goodData ) InputMismatchException be thrown?
prompted again if the input is bad {
System.out.print("Enter an integer: "); yes
try
{
num = scan.nextInt();
goodData = true;
}
catch (InputMismatchException ex )
{
System.out.println("You entered bad data. Please try again.\n" );
String flush = scan.next();
}}
System.out.println("The square of " + num + " is " + num*num );
}}

M. El Dick 10 M. El Dick

yes
Is it correct? How try and catch Work
11 12

try
{ Do not have to catch all
// various statements possible exceptions
}
Some type of exception
catch (InputMismatchException ex )
{
// various statements to handle this type of
exception
}
catch (IOException ex )
Another type of exception
{
// various statements to handle this type of
exception
M. El Dick M. El Dick
}
Types of Exception Types of Exception
13 14

1st matched catch{} gets control In catch{} blocks, a child class should
appear before any of its ancestors
Exception

1st catch{}  most specific Exception type


IOException RunTimeException ParseException Others …
followed by more general Exception types

IndexOutOfBoundsException NoSuchElementException ArithmeticException

InputMismatchException
M. El Dick M. El Dick

import java.util.* ;

Exercise public class DivisionPractice


{
15 public static void main ( String[] a )
{
 Write a program that can: Scanner scan = new Scanner( System.in );
int num=0, div=0 ;
 Get from the user the numerator and the divisor of try{
type integer System.out.print("Enter the numerator: ");
 Perform the division num = scan.nextInt();
System.out.print("Enter the divisor : ");
 Display the result div = scan.nextInt();
System.out.println( num + " / " + div + " is " + (num/div) + " rem " + (num%div) );
}
catch (InputMismatchException ex ){ Reversing order of the 2
System.out.println("You entered bad data." ); blocks also works
System.out.println("Run the program again." );
}
catch (ArithmeticException ex ){
System.out.println("You can't divide " + num + " by " + div);
}}}
M. El Dick 16 M. El Dick
Question The finally{} Block
17 18

 Ifan NoSuchElementException occurs in the try{} try


block, what happens? {
finally{} block always executes
// various statements
}
 Answer: catch (InputMismatchException ex )
finally
 Execution of this method stops { {
 The method throws NoSuchElementExeption up to its // various statements // statements which will execute no matter
caller (the JVM) // how the try block was exited.
}
}
catch (IOException ex )
{
// various statements
}
M. El Dick M. El Dick

How finally{} works Exercise


19 20

 Modify the previous program that can:


 catch ArithmeticException
 print after performing the division: “If something went
wrong, you entered bad data.”
 Show the outputs for the following inputs:
 Numerator = 13; divisor = 4
 Numerator = rats; divisor = 4
 Numerator = 13; divisor = 0

M. El Dick M. El Dick
… Output
try{
System.out.print("Enter the numerator: ");
num = scan.nextInt(); Enter the numerator: 13
System.out.print("Enter the divisor : "); Enter the divisor : 4
div = scan.nextInt(); 13 / 4 is 3 rem 1
System.out.println( num + " / " + div + " is " + (num/div) + " rem " + If something went wrong, you entered bad data.
(num%div) );
Goodbye
}
catch (ArithmeticException ex ){
System.out.println("You can't divide " + num + " by " + div);
} Enter the numerator: rats
finally If something went wrong, you entered bad data.
{ Exception in thread "main"
System.out.println("If something went wrong, you entered bad data." ); java.util.InputMismatchException
} at java.util.Scanner.throwFor(Unknown Source)
} at java.util.Scanner.next(Unknown Source)
System.out.println("Goodbye" );
at java.util.Scanner.nextInt(Unknown Source)
}
at java.util.Scanner.nextInt(Unknown Source)
at FinallyPractice.main(FinallyPractice.java:13)
21 M. El Dick 22 M. El Dick

Output

Enter the numerator: 26


Exception Catch-all
24
Enter the divisor : 0
try {
You can't divide 26 by 0
System.out.print("Enter the numerator: "); num = scan.nextInt();
If something went wrong, you entered bad data.
Goodbye System.out.print("Enter the divisor : "); div = scan.nextInt();
System.out.println( num + " / " + div + " is " + (num/div) + " rem " +
(num%div) );
ArithmeticExceptions are caught in 1st
}
block
catch (ArithmeticException ex ) {
System.out.println("You can't divide " + num + " by " + div);
}
catch (Exception ex ) {
System.out.println("Something went wrong." );
}
System.out.println("Goodbye" );
All other Exceptions are caught in 2nd
block
23 M. El Dick M. El Dick
Exception Objects Exercise
25 26

 Writea program that asks the user for an integer


 Exception objects are Java objects
and for its array index where it is to be placed
 They have methods like:  Only indexes 0 through 9 are allowed
 public void printStackTrace()  Any other index causes an IndexOutOfBoundsException
 Print a stack trace ― a list that shows the sequence
 Use printStackTrace() and getMessage()
of method calls up to this exception

 public String getMessage()


 Return a string that may describe what went wrong

M. El Dick M. El Dick

import java.util.* ;
Output
public class IndexPractice {
public static void main ( String[] a ) { Enter the data: 8
Scanner scan = new Scanner( System.in ); Enter the array index: 10
int data=0, slot=0 ; This is your problem: 10
int[] value = new int[10];
try { Here is where it happened:
System.out.print("Enter the data: "); java.lang.ArrayIndexOutOfBoundsException: 10
data = scan.nextInt(); at IndexPractice.main(IndexPractice.java:18)
System.out.print("Enter the array index: "); Goodbye
slot = scan.nextInt();
value[slot] = data;
}
catch (InputMismatchException ex ) {
System.out.println("This is your problem: " + ex.getMessage() + "\n
Here is where it happened:\n"); Line number in the program where the exception
ex.printStackTrace(); occured.
}
catch (IndexOutOfBoundsException ex ) {
System.out.println("This is your problem: " + ex.getMessage() + "\n
Here is where it happened:\n");
ex.printStackTrace();
}
System.out.println("Goodbye" );
27
}} M. El Dick 28 M. El Dick
Checked Exceptions Checked and Unchecked Exceptions
29 30

Exception CHECKED
 Method must do something about them : IOException CHECKED
 handle the exception in a catch{} block, or AWTException CHECKED
 throw the exception to the caller of the method RunTimeException
ArithmeticException
IllegalArgumentException
 Compiler checks to make sure that this is done NumberFormatException
IndexOutOfBoundsException
NoSuchElementException
InputMismatchException
Others
Others CHECKED

M. El Dick M. El Dick

Checked Exceptions Checked Exceptions


31 32

public static void main ( String[] a )


public static void main ( String[] a ) throws IOException {
{ BufferedReader stdin =
BufferedReader stdin = new BufferedReader ( new InputStreamReader( System.in ) );
new BufferedReader ( new InputStreamReader( System.in ) ); String inData;
String inData;
inData = stdin.readLine(); does not catch try {
// More Java statements ... IOException, inData = stdin.readLine();
} and throws it to its caller }
catch ( IOException ex ) {
// statements to handle the exception
} catches IOException,
Other // More Java statements ... Instead of throwing it to
possibilities? } its caller
M. El Dick M. El Dick
Passing the buck Any method on the chain can catch
33 34

public class BuckPassing { public static void methodC() throws IOException {


public static void methodC() throws IOException { // Some I/O statements
// Some I/O statements }
} public static void methodB() throws IOException {
public static void methodB() throws IOException { methodC();
methodC(); }
} public static void methodA() throws IOException {
public static void methodA() throws IOException { try {
public static void main ( String[] a ) {
methodB(); methodB();
methodA();
} } }}
public static void main ( String[] a ) throws IOException { catch ( IOException ex ) {
methodA(); // statements to handle the exception
}} }
M. El Dick M. El Dick
}

Exercise Exercise (cont’d)


35 36

 Class CallEg that contains : 1. methodA() divides by zero to create an


 3 methods methodA(), methodB(), and methodC() ArithmeticException which is caught by main()
 Class TestTrace that contains :
 main() : creates a CallEg object and calls its methodA() 2. methodC() performs division
methodA() calls methodB() which calls methodC()
P.S. After each try{}, catch the exception, print a stack trace,
and throw the exception object to its caller 3. methodA() calls methodB() inside a try{} block, and
methodB() calls methodC() inside a try{} block, and
methodC() divides inside a try{} block.

M. El Dick M. El Dick
import java.util.* ;

Throwing an Exception public class RateCalc {

37 public static int calcInsurance( int birthYear ) throws Exception {


final int currentYear = 2000;
int age = currentYear - birthYear;
 Design personalized exceptions if ( age < 16 )
throw new Exception("Age is: " + age );
 Can complicate program else {
int drivenYears = age - 16;
if ( drivenYears < 4 ) public static void main ( String[] a ) {
return 1000; Scanner scan = new Scanner( System.in ) );
else System.out.println("Enter birth year:");
return 600; int inData = scan.nextInt();
} try {
} System.out.println( "Your insurance is: " +
calcInsurance( inData ) );
}
catch ( Exception oops ) {
System.out.println( oops.getMessage() + " Too young
for insurance!" );
M. El Dick 38 }}} M. El Dick

Making an Exception Extending Class Exception


39 40

2 constructors for Exception:


 Exception() public class TooYoungException extends Exception
 Exception( String str ) {
 Str can be extracted from the object using TooYoungException ( int age )
getMessage() {
A method can throw a
super( "Age is: " + age ); TooYoungException and a catch{}
} block can catch one
if ( some problem )
throw new Exception("Informative Message" ) ; }

M. El Dick M. El Dick
Exercise Exercise (cont’d)
41 42

 Write a class that contains :  Hints :


 findMin(String[] set) : returns the minimum of  findMin()ignores any negative integer and display
positive integers in set an error message
 Create a new type of exception HandleException for
this
 main() :
 findMin() calls Integer.parseInt(String s) to convert s
public static void main(String[] arg){ into int
String[] t = {“16”, “2x”, “36”, “-64”};
System.out.println(“The minimum is : “ +findMin(t));
}

M. El Dick M. El Dick

Note
43

 Can I override a method that doesn't throw


exceptions with one that does?
 No!!!

M. El Dick

You might also like