Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
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 Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
Lecture 28 More on Exceptions COMP1681 / SE15 Introduction to Programming.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
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.
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 (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
Exceptions COMPSCI 105 S Principles of Computer Science.
CS1101: Programming Methodology Aaron Tan.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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.
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.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
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.
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 
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
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.
Chapter 14 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Testing and Exceptions
Announcements/Reminders
Exception Handling Chapter 9.
Exceptions & exception handling
ATS Application Programming: Java Programming
Exceptions & exception handling
Exception Handling Chapter 9 Edited by JJ.
Fundamental Error Handling
Lecture 11 Objectives Learn what an exception is.
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
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University

Announcements Project 6 is out  2 week project  Milestone Due October 29, 10:00pm  Final Submission Due November 5, 10:00pm This is the date of Exam 2, so start early on the project!

Introduction An exception is an object  Signals the occurrence of unusual event during program execution Every program should handle possible exceptions.  Throw an exception when something goes wrong.  Catch the exception – handle the unusual event.

Why do we need exception handling ? Recover from errors! Consider this simple program: import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter a number:"); int number = keyboard.nextInt(); System.out.println(number); } What if the user types ”fifteen” ? The program crashes with InputMismatchException

Test Class (with appropriate exception handling) import java.util.Scanner; import java.util.InputMismatchException; public class Test { public static int DEFAULT_NUMBER = 5; public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter a number:"); int number; try{//code where something could go wrong number = keyboard.nextInt(); } catch(InputMismatchException e){ //code executed if an InputMismatchException is thrown number = DEFAULT_NUMBER; System.out.println("Bad input!!! Setting the number to default value, “+ number); } System.out.println(number); }

Test Class (Handling multiple exceptions) A try-catch statement can have multiple catch blocks to handle multiple possible exceptions. Example - public class Test { public static void main(String args[]) { int number, divisor, quotient; try{ number = keyboard.nextInt(); System.out.println("Please enter the divisor:"); divisor = keyboard.nextInt();//The user can enter an illegal value here quotient = number/divisor; //The user could have entered 0 for divisor! } catch (InputMismatchException e){ number = divisor = DEFAULT_NUMBER; System.out.println("Bad input!!! Setting the default value, “ + number); } catch (ArithmeticException e){ System.out.println(“Division by zero”); }

Handling multiple exceptions If an exception occurs at the first line of the try block, the control transfers to the corresponding catch block.  This causes code to be skipped. Solutions:  If there is a way to handle exception without a try-catch block, use it. Example – check for divisor being 0 before dividing. This is the best way to deal with problems.  For each statement, form a different try-catch block and catch every possible exception.

Handling multiple exceptions When an exception is thrown in a try block, the catch blocks are checked in order for the matching exception 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 inverse = 1/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 the exceptions will be caught by the first catch block. This causes a compile error. These two catch blocks should be swapped.

9 Defining Your Own Exception Classes For handling problems of a specific type, it is better to design a specific exception class rather than using the Exception class. Must be a derived class of some predefined exception class, e.g Exception, InputMismatchException etc. Example: a more specific exception class for division by 0. class DivideByZeroException extends ArithmeticException { public DivideByZeroException(){ super("Dividing by Zero!"); } public DivideByZeroException(String message) { super(message); }

Implementing New Exception Classes Defining your own exception class just gives you the ability to throw and catch objects of that class. Catch handlers are not part of the user-defined exception classes In other words you should explicitly indicate in your program when to throw your own exception Example: try { if (divisor == 0) throw new DivideByZeroException(“The divisor is zero”); } catch(DivideByZeroException e) { System.out.println(e.getMessage(); }

An example with multiple user-defined exception classes Here’s a simple program that distributes a number of eggs into some baskets equally. public class Test { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); try{ System.out.println("Please enter the number of eggs:"); int numberOfEggs = keyboard.nextInt(); System.out.println("Please enter the number of baskets:"); int numberOfBaskets = keyboard.nextInt(); if(numberOfEggs < 0 || numberOfBaskets < 0) throw new NegativeNumberException(“Number of eggs/baskets cannot be negative”); if(numberOfBaskets==0) throw new DivideByZeroException(“No baskets?”); ….. } catch(DivideByZeroException e){…… } catch(NegativeNumberException e){…… } }

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.  e.g int quotient(int dividend, int divisor) throws DivideByZeroException { …. }  The method quotient might throw a DivideByZeroException object in its body but not handle it in a try-catch block. All this tells the compiler is that any method that calls quotient(..) is responsible for handling the thrown exception.

Accounting for Exceptions Example – int quotient(int dividend, int divisor) throws DivideByZeroException { if(divisor==0) throw new DivideByZeroException(); return dividend/divisor; } int main(String args[]) { try { int q = quotient(3, 0); }//catching exception where the method is called catch(DivideByZeroException e) { System.out.println(e.getMessage()); }

Accounting for Exceptions Exceptions are thrown in one method and handled in another  Multiple methods calling the same function can handle errors differently. Some method in the calling hierarchy should handle the exception  If method c() declares that it throws an exception, then method b() can either catch it or pass the buck in turn. If an exception is thrown, but never caught, the program terminates. main() a() b()c()

Keep It Simple Handling exceptions in the same method where they are thrown makes things too specific. If the way the exception is to be handled depends on the calling method, let the calling method handle the exception  This is a good programming practice.

throws Clause Not Allowed in actionPerformed A throws clause cannot be added to method actionPerformed in any action listener class. Any exception thrown in the method actionPerformed must be caught within.

Quiz Scanner keyboard = new Scanner(System.in); int number = 0; try{ number = 10/keyboard.nextInt()-keyboard.nextInt(); } catch (ArithmeticException e){ number = 8; } catch (InputMismatchException e) { number = 3; } Assume a user tries to enter 0 first, then “five”. What is the value of number at the end?