Unit 10 1 Exception Handling H Run-time errors H The exception concept H Throwing exceptions H Handling exceptions H Declaring exceptions basic programming.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
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.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Preventing and Correcting Errors
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
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.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
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 and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exceptions In this lecture:
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Chapter 12 Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
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
Exceptions 10-May-19.
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

unit 10 1 Exception Handling H Run-time errors H The exception concept H Throwing exceptions H Handling exceptions H Declaring exceptions basic programming concepts object oriented programming in Java topics in computer science syllabus

unit 10 2 Run-time errors H Sometimes when the computer tries to execute a statement something goes wrong: reading a file that does not exist or is inaccessible dividing a number by zero calling a method with improper arguments H In these cases we say that a run-time error has occurred H In Java, run-time errors are indicated by exceptions

unit 10 3 Exceptions H If a method wants to signal that something went wrong during its execution, it throws an exception; exceptions may be caught and handled by another part of the program H Throwing an exception involves: creating an exception object that encloses information about the problem that occurred use of the statement throw to notify about the exception H A program can therefore be separated into a normal execution flow and an exception execution flow

unit 10 4 Example: throwing an exception // Sets the time of the clock hour, minute, second - Tthe new time public void setTime(int hour, int minute, int second) { if (hour 59 || minute 59 || second 59) { throw new IllegalArgumentException( “Invalid time”); } this.hour = hour; this.minute = minute; this.second = second; }

unit 10 5 The exception object H The information about the problem that occurred is enclosed in an exception object, including: The type of the problem The place in the code where the exception occurred The state of the run-time stack... other information H An exception object comes with service methods such as getMessage or printStackTrace H The code that invoked the illegal operation will receive the exception object

unit 10 6 The type of the exception H The most important information is the type of the exception, indicated by the class of the exception object H The Java API defines classes for many types of exceptions (and you can define more of your own): java.lang.ArithmeticException - thrown when an exceptional arithmetic condition occurs, e.g., division by zero java.io.FileNotFoundException - signals that a file we tried to access could not be found java.net.UnknownHostException - signals that a computer we tried to communicate with cannot be located NullPointerException - trying to refer to an object through a reference variable whose value is null

unit 10 7 Example  The setTime() method used the exception java.lang. IllegalArgumentException to signal that the values of the arguments were not valid H A method throws this type of exception if it wants to signal that an argument it got is not legal

unit 10 8 Occurrence of an exception H When a program performs an illegal operation the following happens: An exception object is created and thrown The regular flow of the program stops The program may try to handle the exceptional situation If the program ignores the exception, execution stops; we sometimes say that the program crashed

unit 10 9 Occurrence of an exception //... class BucketsProblem { public static void main(String[] args) { //... int targetCapacity = 2*x-y; Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(targetCapacity); //... } H What happens if x<0 or y<0 or 2x-y<0 ?

unit The root of the exception in class Bucket (Bucket.java): // Constructs a new Bucket. capacity: the capacity of the bucket IllegalArgumentException if the // given capacity is negative public Bucket(int capacity) { if (capacity<0) { throw new IllegalArgumentException( “Capacity must be positive!”); } this.capacity = capacity; }

unit Occurrence of an exception public static void main(String[] args) { //... int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } A bucket must have a positive capacity Hey, no one cares to listen! I’ll crash the method! x = -3

unit Occurrence of an exception public static void main(String[] args) { //... int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } A bucket must have a positive capacity. No one cares,... I’ll crash the method x = -3 public Bucket(int capacity) { if (capacity<0) { throw new IllegalArgumentException( “Capacity must be positive!”); } this.capacity = capacity; } capacity = -3

unit Exceptions happen H Sometimes we cannot avoid an exceptional state; for example when reading from a diskette we cannot tell if the diskette is readable or not without trying to read from it H Sometimes we want to handle the exceptional case outside the main block, so as not to complicate the readability of the code H If we ignore the exception, the program crashes

unit Exception Handling H A program can deal with an exception in one of three ways: ignore it (the program will ‘crash’) handle it where it occurs handle it an another place in the program

unit Handling Exceptions H To process an exception when it occurs, the line that throws the exception is executed within a try block H A try block is followed by one or more catch clauses, which contain code to process an exception H Each catch clause has an associated exception type H When an exception occurs, processing continues at the first catch clause that matches the exception type

unit Handling exceptions public static void main(String[] args) { //... try { int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } catch (IllegalArgumentException ia) { output.println(“Illegal input!”); } A bucket must have a positive capacity

unit Handling exceptions public static void main(String[] args) { //... try { int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } catch (ArithmeticException ae) { //... } catch (IllegalArgumentException ia) { output.println(“Illegal input!”); } A bucket must have a positive capacity

unit The finally Clause  A try statement can have an optional clause designated by the reserved word finally H If no exception is generated, the statements in the finally clause are executed after the statements in the try block finish their execution H In addition, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete execution

unit Exception Propagation H If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level H Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level H Any try block along the way, that contains a call to a method in which an exception is thrown, can be used to catch that exception

unit The throw Statement H A programmer can define an exception by extending the appropriate class  Exceptions are thrown using the throw statement H Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown

unit Generating Exception Objects H All the classes for indicating run-time errors are derived from the class java.lang.Throwable  The object you deliver to the throw statement must be an instance of class Throwable H The constructor of class Throwable initializes all the information about the location where the exception occurred, the state of the run-time stack etc (thus this information is set for every exception object)

unit Exceptions class hierarchy Throwable Exception Error RuntimeException

unit Exception & Error distinction H java.lang.Throwable has two direct subclasses: java.lang.Error and java.lang.Exception H Every run-time error is identified by a class that is either a subclass of Error or of Exception H The distinction is not very strict: Error refers to run-time errors that are rooted in the execution environment and are not in the hands of the application programmer Exception refers to all other run-time errors; the application programmer is responsible to see that all exceptions are handled

unit Errors examples  java.lang.InternalError - signals an error caused by an implementation bug in the JVM in which the application is running; the developer is not responsible for this error and should not try to handle it  java.lang.NoSuchMethodError - signals that a method that the application is trying to use does not exist; this may happen if the application is not installed correctly  java.lang.OutOfMemory - signals that the application ran out of memory

unit Exception examples  java.lang.ArithmeticException - occurs when you divide an integer by 0; the exception is rooted in the logic of the application, hence it is the programmer responsibility to handle it  java.io.FileNotFoundException - occurs when the application tries to access a file which does not exist; again, the programmer should treat this case H...

unit Errors and Exceptions H The application you write must handle all Exceptions but ignore Errors: If an Error occurs you should let it crash the application; the user will be notified for the error and act accordingly (buy more memory, reinstall the application, call tech support...) On the other hand, it’s very uncool to let the application crash because you didn’t catch an exception

unit Exceptions class hierarchy Throwable Exception Error RuntimeException

unit Exceptions vs. RuntimeExcepiton  Class Exception has a special subclass named RuntimeException, which makes another classification of exceptions: runtime-exceptions vs. regular exceptions H RuntimeException is characterized by: The programmer could avoid the occurrence of the exception The exception can be thrown by common statements/methods H The name RuntimeException is confusing; every exception and Error occurs during the run-time of the application

unit RuntimeException examples H java.lang.ArithmeticException H java.lang.NullPointerException H java.lang.IllegalArgumentException H java.lang.NegativeArraySizeException H java.lang.ArrayIndexOutOfBoundsException

unit Declaring for exceptions H A method must declare all the non run-time exceptions it may throw  The declaration for exceptions a method can throw is done using the throws keyword H The user of the method is warned against possible exceptions this method can throw H The exceptions that might be thrown by a method should also be documented with tag

unit Example (using throws) // Creates an ElectronicGate of a given type public ElectronicGate createGate(String type) throws UnkownGateException { type = type.toUpperCase(); if (type.equals(“OR”)) { return new OrGate(); } if (type.equals(“AND”)) { return new AndGate(); } if (type.equals(“NOT”)) { return new NotGate(); } throw new UnknownGateException(); }

unit Declaring for exceptions H Because there is a possibility that an execution of createGate() will throw an UnknownGateException which is not a RuntimeException, createGate() must declare this exception H If you try to call the createGate() method from another method, the compiler will know that there is a possibility that this method will throw an UnknownGateException; it will then force you to: try to catch this exception or declare that the calling method also throws this type of exception

unit Example: either catch... // Called when the user chooses to add a gate private void userAddsGate() { String type =... look up the selected gate type try { Gate gate = createGate(type); GateFigure figure = createGateFigure(type);... adds the gate to the model... add the figure to the display... } catch (UnknownGateException uge) { // ignore this, don’t add the gate } }

unit or declare // Called when the user chooses to add a gate private void userAddsGate() throws UnknownGateException { String type =... look up the selected gate type Gate gate = createGate(type); GateFigure figure = createGateFigure(type);... adds the gate to the model... add the figure to the display... }

unit Defining new exception type // An exception thrown to indicate that a requested // type of electronic gate does not exist public class UnknownGateException extends Exception { // Creates a new UnknownGateException public UnknownGateException() { super(“This is an illegal gate type!”); } // Creates a new UnknownGateException public UnknownGateException(String cause) { super(cause); } }

unit Several notes H The throws statement doesn’t affect the way the exception will be treated in run-time H You can also declare for RuntimeExceptions, but it is not necessary H When to declare and when to catch the exception within the method is a design decision

unit Exaple: class MyDate public class MyDate { public static final int JANUARY= 1; public static final int FEBRUARY= 2; //data members public int day; private int month; private int year; //default constructor - recieves no paramaters public MyDate() { day= 1; month= 1; year= 2000; }

unit Exaple: class MyDate //insertion constructor public MyDate(int day,int month,int year) throws IllegalMyDateException { if (!legalDate(day,month,year)) throw new IllegalMyDateException(); this.day= day; this.month= month; this.year= year; } private boolean legalDate(int day,int month,int year){ if ( (day 31) || (month 12) ) return(false); return(true); } }

unit Exception class definition public class IllegalMyDateException extends Exception { public IllegalMyDateException(String message){ super(message); } public IllegalMyDateException(){ super("this is not a legal date!"); } }