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.

Slides:



Advertisements
Similar presentations
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
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.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
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.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
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.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Advanced Flow of Control - Introduction - zTwo additional mechanisms for controlling process execution are exceptions and threads zChapter 14 focuses.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
10-1 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are thrown by a program, and may be caught and handled.
Java Software Solutions Lewis and Loftus Chapter 14 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Advanced Flow of Control --
Chapter 10 Exceptions. Chapter Scope The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception propagation The.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
© 2004 Pearson Addison-Wesley. All rights reserved April 24, 2006 Exceptions (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING 2006.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
© 2004 Pearson Addison-Wesley. All rights reserved December 5, 2007 I/O Exceptions & Working with Files ComS 207: Programming I (in Java) Iowa State University,
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
CSE 1201 Object Oriented Programming
Java Exceptions a quick review….
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
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.
Exceptions (part 2) December 3, 2007 ComS 207: Programming I (in Java)
Exception Handling.
Presentation transcript:

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 the program to actually determine the values of variables, get user input, etc. These errors that occur when the program is running are “exceptions”

3 Exceptions An exception is an object that describes an unusual or erroneous situation Exceptions are generated by part of a program, and may be handled by another part of the program A program can be separated into a normal execution flow and an exception execution flow An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught

4 Exception Handling Java has a predefined set of exceptions and errors that can occur during execution A program can deal with an exception in one of three ways:  ignore it  handle it where it occurs  handle it an another place in the program The manner in which an exception is processed is an important design consideration

Exception Handling If an exception isn’t handled by the program, it halts and prints an error: Exception in thread “main” java.lang.NullPointerException at SomeClass.method(SomeClass.java:54) at Except.e2(Except.java:12) at Except.main(Except.java:22) The error message gives the type of exception that was thrown ( NullPointerException ) and the “stack trace”…

6 The Call Stack Trace Indicates the line on which the exception occurred  (SomeClass.java:54) Shows the method call trail that lead to the attempted execution of the offending line  main → e2 → method

Tracing Problems The call stack can be very long, and call methods in many libraries Exception in thread “main” java.util.UnknownFormatConversionException: Conversion = ‘i’ at java.util.Formatter$FormatSpecifier.conversion(Formatter.java:2603) at java.util.Formatter$FormatSpecifier. (Formatter.java:2631) at java.util.Formatter.parse(Formatter.java:2477) at java.util.Formatter.format(Formatter.java:2411) at java.io.PrintStream.format(PrintStream.java:899) at java.io.PrintStream.printf(PrintStream.java:800) at Except.e3(Except.java:17) at Except.main(Except.java:22) It can be tricky to find the “real” cause  should be the innermost code that isn’t fully tested

The Exception Class In Java, exceptions are objects There is a hierarchy of exception types, with Exception at the top  you don’t generally instantiate Exception ; one is automatically created when there is an error There are many subclasses of Exception that are used for particular types of errors

Exception Subclasses The subclasses of Exception are types that more specifically identify the problem, e.g.:  ArithmeticException most often caused by a divide-by-zero  IndexOutOfBoundsException array/List/String index doesn’t exist  NoClassDefFoundError.class file was there when compiling, but not there now Tend to have informative names: useful errors

10 The Exception Class Hierarchy All error and exception classes are descendents of the Throwable class A programmer can define an exception by extending the Exception class or one of its descendants The parent class used depends on how the new exception will be used

Catching Exceptions We say that a certain block of code “throws” an exception  think: when the exception occurs, an exception object is generated and tossed at the interpreter How do you handle something that is thrown at the interpreter?  you “catch” it Uncaught exceptions stop the program… caught exceptions do not

12 The try Statement To handle an exception in a program, the line that throws the exception is executed within a try block A try block is followed by one or more catch clauses Each catch clause has an associated exception type and is called an exception handler When an exception occurs, processing continues at the first catch clause that matches the exception type

A try/catch sequence try { \\ execute the code that you find here } catch(Exception e) { \\ if the there is an exception \\ then you do the stuff in this part }

An Example try { int x; x = 10/0; } catch(Exception e) { System.out.println(“error occurred”); }

The Exception Parameter The catch is a little like an else, and a little like a function definition  try {…} catch(Exception e) {…}  The argument (“exception parameter”) is assigned to an appropriate Exception object  In the divide-by-zero example, e will be an instance of ArithmeticException The exception parameter’s value can be ignored if you don’t need to use it

Another Example try { int x; x = 10/0; } catch(ArithmeticException e) { System.out.println(“divided by 0”); }

Being Specific Can have multiple catch blocks The exception parameter type allows different types of exceptions to be handled differently

Being Specific try { int x = userin.nextInt(); System.out.println(10/x); } catch(ArithmeticException e) { System.out.println(“no zeroes”); } catch(InputMismatchException e) { System.out.println(“enter a number”); } Most likely causes

Being Specific The exception parameter is matched like arguments in an overloaded function  The type of exception thrown is matched against the exception parameters  That class… or any subclass… will match Examples:  Exception matches all exceptions  IndexOutOfBounds matches both array and string exceptions

The Catch All try { … a bunch of code, involving an integer x… System.out.println(10/x); } catch(ArithmeticException e) { System.out.println(“no zeroes”); } catch(Exception e) { System.out.println(“some other problem”); }

However… In general, use a type as specific as possible  only catch the exceptions you want to catch and handle properly  Don’t incorrectly handle other problems the catch-all hides problems you might want to know about Other exceptions are propogated  they can be caught farther up the call stack

22 Exception Propagation An exception can be handled at a higher level if it is not appropriate to handle it where it occurs Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the level of the main method A try block that contains a call to a method in which an exception is thrown can be used to catch that exception

Checked versus Unchecked An exception is either checked or unchecked An unchecked exception does not require explicit handling, though it could be processed that way The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants in that:  Errors should not be caught  Errors do not require a throws clause

24 Checked Exceptions Checked exceptions (other subclasses of Exception ) must be handled explicitly  must be caught by a method in a catch block  must be listed in the throws clause of any method that might throw it The compiler will issue an error if a checked exception is not caught or asserted in a throws clause

The throws Clause Used to indicate that the method will “handle” the checked exception by passing it off to the calling code  Similarly, the calling code must either catch it or be declared indicating that it throws the exception public int myMethod() throws Exception1, Exception2 Any uncaught checked exceptions must be listed in the throws clause

The throw Statement When your code gets to a situation it can’t handle, it can throw an exception  e.g. constructor/setter given an illegal value Create an instance of the appropriate exception class  new SomeException(“Error message”); Throw the exception with a throw statement  throw new SomeException(“message”);

27 The throw Statement The throw statement appears in the body of a method, with an appropriate throws clause Usually a throw statement is executed inside an if statement that evaluates a condition to see if the exception should be thrown if(x<0) throw new NegativeInputException;

Example From the Student class: public void setFirstName(String name) { if(name.length()>0) firstName = name; else throw new IllegalArgumentExceptionIllegalArgumentException (“Name must have length >0”); }

29 The finally Clause A try statement can have an optional clause following the catch clauses, designated by the reserved word finally The statements in the finally clause always are executed If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete If an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete

Why use finally ? To make sure that a certain part of an algorithm are executed To leave objects in a stable state  e.g. An object representing a database connection might be disconnected when an error occurs  … there are good security reasons for doing this