Exception Handling (Chapter 8), Lecture notes of Accounting

public class Test. { public static int DEFAULT_EGGS = 5; public static void main(String[] args). {. Scanner keyboard = new Scanner(System.in);.

Typology: Lecture notes

2022/2023

Uploaded on 02/28/2023

courtneyxxx
courtneyxxx 🇺🇸

4.5

(14)

253 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Exception Handling (Chapter 8)
CS 180 Recitation - February 29, 2008
Department of Computer Science
Purdue University
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Exception Handling (Chapter 8) and more Lecture notes Accounting in PDF only on Docsity!

Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008Department of Computer SciencePurdue University

Announcements •^ Projects are examined by software thatdetects potential cheating •^ Project 4 handed back •^ Project 4 test cases are posted. Beforeregrade request, test your program withthem. For regrade, contact with

Jalaja

Padma

Introduction •^ To handle exceptions, Java’s exceptionhandling facilities should be used. •^ 2 sections of a program:

•^ Code segments that handle normal flow ofcontrol. •^ Code segments that handle the exceptionalcases that might occur through out theexecution.

Test Class Consider this simple program:

import java.util.InputMismatchException;import java.util.Scanner;public class Test{

public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);System.

out .println("Please enter the number of eggs:");

int numberOfEggs = keyboard.nextInt();System.out.println(numberOfEggs);

Test Class (Right Way) import java.util.Scanner;public class Test{ public static int DEFAULT_EGGS = 5;public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);System.out.println("Please enter the number of eggs:");int numberOfEggs;try{

numberOfEggs = keyboard.nextInt(); } catch(Exception e){

numberOfEggs = DEFAULT_EGGS;System.out.println("Bad input!!!\nSetting the default value, "

  • numberOfEggs);

} System.out.println(numberOfEggs); } }

Test Class (Handling multiple exceptions) import java.util.Scanner;public class Test{ public static int DEFAULT_EGGS = 5;public static void main(String[] args){

Scanner keyboard = new Scanner(System.in);System.out.println("Please enter the number of eggs:");int numberOfEggs = 0;int numberOfBasket = 0;int eggsPerBasket = 0;try{

numberOfEggs = keyboard.nextInt();System.out.println("Please enter the number of baskets:");numberOfBasket = keyboard.nextInt();eggsPerBasket = numberOfEggs/numberOfBasket; } catch(Exception e){

//Opps, now what to catch? Bad user input or division by zero? } System.out.println(numberOfEggs); } }

Handling multiple exceptions •^ Although it catches multiple exceptions, thispiece of code doesn’t execute all the statementsif an exception occurs at the first line of try block. •^ If there is a way to handle exception without atry-catch block, use it. (i.e. instead of using^ ArithmeticException

an if statement that checks if

numberOfBasket<

would suffice)

-^ For each statement, form a different try-catchblock and catch every possible exception.

Handling multiple exceptions •^ While catching exceptions, it is crucial that order goesfrom specific exception (sub-class) to general exception(parent class) since the first matching catch is executed.

Scanner keyboard = new Scanner(System.in);try{

int tmp = 10/keyboard.nextInt() - keyboard.nextInt();

} catch (

Exception

e){

e.printStackTrace();

} catch (

InputMismatchException

e){

System.out.println(e.getMessage());

CompileError

Parent Class

Sub-class of Exception

The flow of control will never go into the last catchblock since all of the exception will be caught by thefirst catch block. This will cause a compile error.So, these 2 catch blocks should be swapped.

Accounting for Exceptions (

st^ option)

-^ Catching an exception inside of a method^ import java.util.InputMismatchException;import java.util.Scanner;public class Test{

public static void main(String[] args){

int numberOfEggs = getInput("Please enter the number of eggs:", 1);int numberOfBasket = getInput("Please enter the number of baskets:", 1);if (numberOfBasket < 1)

numberOfBasket = 1; int eggsPerBasket = numberOfEggs/numberOfBasket;System.out.println(numberOfEggs+"-"+numberOfBasket+"-"+eggsPerBasket); } public static int getInput(String prompt, int numOfTry){

Scanner keyboard = new Scanner(System.in);System.out.println(prompt);int k = 0;try{

k = keyboard.nextInt(); } catch(InputMismatchException e){

System.out.println("Bad input!!!(try number: "+numOfTry+")");k = getInput(prompt, numOfTry+1); } return k; } }

Accounting for Exceptions (

nd^

option)

-^ Catching an exception where the method is called^ public

static

void main(String[]

args)

int numberOfEggs

try{

numberOfEggs = getInput("Please

enter

the^ number

of^ eggs:");

}^ catch

(InputMismatchException

e){

numberOfEggs = 5; } int numberOfBasket =

try{

numberOfBasket =

getInput("Please

enter

the^ number

of^ baskets:");

}catch

(InputMismatchException

e){

numberOfEggs = -1;numberOfBasket =

… } public

static

int^ getInput(String

prompt)

throws

InputMismatchException{

Scanner

keyboard

= new Scanner(System.in);

System.out.println(prompt);int k =

keyboard.nextInt(); return

k;

}

Keep It Simple •^ If the way the exception is handleddepends on the calling method, let thecalling method handle the exception (i.e.^2

nd^ option, in the second try-catch the firstvariable is changed used in the first try-catch).

•^1

st^ option is more specific and is less likelyto be used through out the program, so itis a good practice to implement 2

nd^ option.

Implementing New ExceptionClasses •^ Don’t forget catch handlers won’t be partof user-defined exception classes •^ In other words you should explicitlyindicate in your program when to throwyour own exception •^ Test class example continued:

throws

Clause Not Allowed in

actionPerformed •^ A throws clause cannot be added to methodactionPerformed in any action listener class. •^ Any exception thrown in methodactionPerformed must be caught in methodactionPerformed. •^ Similarly, if method windowClosing is redefinedin a window listener class, you may not add athrows clause to method windowClosing.

Quiz Scanner

keyboard

=^ new

Scanner(System.in);

int^ tmp

=^ 0;

try{tmp

=^ 10/keyboard.nextInt()

  • keyboard.nextInt();

}^ catch

(InputMismatchException

e){

System.out.println(“InputMismatchException”);tmp^ =

}^ catch

(Exception

e){

System.out.println(“Exception”);tmp^ =

} Assume a user tries to enter 0 first, then 5. What is the value of tmp at the end?