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

Slides:



Advertisements
Similar presentations
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Advertisements

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.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
Exception Handling By: Thomas Fasciano. What is an Exception?  An error condition that occurs during the execution of a Java Program.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
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.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exception Handling. Lecture Objectives To learn how to throw exceptions To be able to design your own exception classes To understand the difference between.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CS1101: Programming Methodology Aaron Tan.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
Computer Science [3] Java Programming II - Laboratory Course Lab 3-1: Creating and Using Interfaces Exception Faculty of Engineering & IT Software Engineering.
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. Exception Abnormal event occurring during program execution Examples –Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
Lecture 14 Throwing Custom Exceptions
Chapter 10 – Exception Handling
Testing and Exceptions
Something about Java Introduction to Problem Solving and Programming 1.
BIT115: Introduction to Programming
Exceptions & exception handling
Phil Tayco Slide version 1.0 Created Nov. 26, 2017
Exceptions & exception handling
Fundamental Error Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
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 Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Basic Exception Handling
Presentation transcript:

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

Announcements Projects are examined by software that detects potential cheating Project 4 handed back Project 4 test cases are posted. Before regrade request, test your program with them. For regrade, contact with Jalaja Padma

Introduction Exceptions are cases that change a program’s normal flow of control. Every program should handle possible exceptions. Assuming nothing will go wrong through out the program execution is wrong. After all; anything that can go wrong, will go wrong.

Introduction To handle exceptions, Java’s exception handling facilities should be used. 2 sections of a program: Code segments that handle normal flow of control. Code segments that handle the exceptional cases that might occur through out the execution.

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 Problem: What if the user types “4” instead of 4. Please enter the number of eggs: “4” Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at Test.main(Test.java:11) Unacceptable if the user doesn’t know Java

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

Test Class (Handling multiple exceptions) import java.util.InputMismatchException; import java.util.Scanner; public class Test { ……………. try{ numberOfEggs = keyboard.nextInt(); System.out.println("Please enter the number of baskets:"); numberOfBasket = keyboard.nextInt(); eggsPerBasket = numberOfEggs/numberOfBasket; } catch(InputMismatchException e){ numberOfEggs = DEFAULT_EGGS; System.out.println("Bad input!!!\nSetting the default value, " + numberOfEggs); } catch(ArithmeticException e){ System.out.println(“Division by zero”); numberOfBasket = 1; eggsPerBasket = numberOfEggs; } System.out.println(numberOfEggs); }

Handling multiple exceptions Although it catches multiple exceptions, this piece of code doesn’t execute all the statements if an exception occurs at the first line of try block. If there is a way to handle exception without a try-catch block, use it. (i.e. instead of using ArithmeticException an if statement that checks if numberOfBasket<1 would suffice) For each statement, form a different try-catch block and catch every possible exception.

Handling multiple exceptions While catching exceptions, it is crucial that order goes from 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()); } Compile Error Parent Class Sub-class of Exception The flow of control will never go into the last catch block since all of the exception will be caught by the first catch block. This will cause a compile error. So, these 2 catch blocks should be swapped.

Accounting for Exceptions An exception can be caught in a catch block within a method definition. Alternatively, the possibility of an exception can be declared at the start of the method definition by placing the exception-class name in a throws clause. These two approaches can be mixed in a method, catching some exceptions and declaring others in a throws clause.

Accounting for Exceptions (1 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 (2 nd option) Catching an exception where the method is called public static void main(String[] args) { int numberOfEggs = 0; try{ numberOfEggs = getInput("Please enter the number of eggs:"); } catch (InputMismatchException e){ numberOfEggs = 5; } int numberOfBasket = 0; try{ numberOfBasket = getInput("Please enter the number of baskets:"); }catch (InputMismatchException e){ numberOfEggs = -1; numberOfBasket = -1; } … } public static int getInput(String prompt) throws InputMismatchException{ Scanner keyboard = new Scanner(System.in); System.out.println(prompt); int k = keyboard.nextInt(); return k; }

Accounting for Exceptions Some method in the calling hierarchy should handle the exception (i.e. either getInput or main method). If an exception is thrown, but never caught, either the program terminates or its behavior becomes unreliable.

Keep It Simple If the way the exception is handled depends on the calling method, let the calling method handle the exception (i.e. 2 nd option, in the second try-catch the first variable is changed used in the first try- catch). 1 st option is more specific and is less likely to be used through out the program, so it is a good practice to implement 2 nd option.

Implementing New Exception Classes Don’t forget catch handlers won’t be part of user-defined exception classes In other words you should explicitly indicate in your program when to throw your own exception Test class example continued:

Test Class (Cont.) 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); try{ if (numberOfBasket < 1) throw new DivideByZeroException(); } catch (DivideByZeroException e) { System.out.println(e.getMessage()); numberOfBasket = 1; } int eggsPerBasket = numberOfEggs/numberOfBasket; System.out.println(numberOfEggs+"-"+numberOfBasket+"-"+eggsPerBasket); } public static int getInput(String prompt, int numOfTry){…} } class DivideByZeroException extends Exception { public DivideByZeroException() { super("Dividing by Zero!"); } public DivideByZeroException(String message) { super(message); }

throws Clause Not Allowed in actionPerformed A throws clause cannot be added to method actionPerformed in any action listener class. Any exception thrown in method actionPerformed must be caught in method actionPerformed. Similarly, if method windowClosing is redefined in a window listener class, you may not add a throws 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 = -1 } catch (Exception e){ System.out.println(“Exception”); tmp = -2; } Assume a user tries to enter 0 first, then 5. What is the value of tmp at the end?