I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10.

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
© 2012 Pearson Education, Inc. All rights reserved. Chapter 12: Exceptions and Advanced File I/O Starting Out with Java: From Control Structures through.
Objectives In this chapter you will: Learn what an exception is Learn how to handle exceptions within a program See how a try / catch block is used to.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Starting Out With Java 5 (Early Objects) Chapter 10 By Tony Gaddis Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Chapter 12 By Tony Gaddis Modified by Elizabeth Adams Copyright © 2005 Pearson Addison-Wesley. All rights reserved.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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 Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
12-2 Chapter Topics Chapter 12 discusses the following main topics: Part I: Exceptions Handling Exceptions Throwing Exceptions Part II: More about Input/Output.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
COP INTERMEDIATE JAVA Exception Handling Serialization.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Exceptions and Exception Handling (continued) Carl Alphonce CSE116.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
12.1 Exceptions The limitations of traditional methods of exception handling Error conditions are a certainty in programming Programmers make.
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.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
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.
COMPUTER PROGRAMMING 2 Exceptions. What are Exceptions? Unexpected events that happen when the code is executing (during runtime). Exceptions are types.
Exceptions and Advanced File I/O
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
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.
© Mohamed Nuzrath Java Programming :: Chapter 6 :: Prepared & Presented By :: Mohamed Nuzrath [ Major In Programming ] NCC Programme coordinator IT Lecturer.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 10 Exceptions and Advanced File I/O.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
C# Exceptions 1 CNS 3260 C#.NET Software Development.
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Chapter 12: Exceptions and Advanced File I/O
CS-0401 INTERMEDIATE PROGRAMMING USING JAVA
Chapter 11—Exceptions Handling Exceptions Throwing Exceptions.
Chapter 11: Exceptions and Advanced File I/O
Topics Introduction to File Input and Output
Chapter 12 Exception Handling
Handling Exceptions.
Chapter 12: Exceptions and Advanced File I/O
Topics Introduction to File Input and Output
Presentation transcript:

I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects CS 146 Class Notes Fall 10

12-2 Chapter Topics Chapter 12 discusses the following main topics: Handling Exceptions Throwing Exceptions

12-3 Handling Exceptions An exception is an object that is generated as the result of an error or an unexpected event. Exception are said to have been “thrown.” It is the programmers responsibility to write code that detects and handles exceptions. Unhandled exceptions will crash a program. Example: BadArray.javaBadArray.java Java allows you to create exception handlers.

12-4 Handling Exceptions The process of intercepting and responding to exceptions is called exception handling. The default exception handler deals with unhandled exceptions and prints an error message and crashes the program.

12-5 Exception Classes An exception is an object. Exception objects are created from classes in the Java API hierarchy of exception classes. All of the exception classes in the hierarchy are derived from the Throwable class. Error and Exception are derived from the Throwable class.

12-6 Exception Classes Classes that are derived from Error : are for exceptions that are thrown when critical errors occur. (i.e.) an internal error in the Java Virtual Machine, or running out of memory. Applications should not try to handle these errors because they are the result of a serious condition. Programmers should handle the exceptions that are instances of classes that are derived from the Exception class.

12-7 Exception Classes Object Throwable ExceptionError RuntimeExceptionIOException FileNotFoundExceptionEOFException … … … …

12-8 Handling Exceptions To handle an exception, you use a try statement. try { (try block statements...) } catch (ExceptionType ParameterName) { (catch block statements...) } First the keyword try indicates a block of code will be attempted (the curly braces are required). This block of code is known as a try block.

12-9 Handling Exceptions A try block is: one or more statements that are executed, and can potentially throw an exception. The application will not halt if the try block throws an exception. After the try block, a catch clause appears.

12-10 Handling Exceptions A catch clause begins with the key word catch : catch (ExceptionType ParameterName) ExceptionType is the name of an exception class and ParameterName is a variable name which will reference the exception object if the code in the try block throws an exception. The code that immediately follows the catch clause is known as a catch block (the curly braces are required). The code in the catch block is executed if the try block throws an exception.

12-11 Handling Exceptions This code is designed to handle a FileNotFoundException if it is thrown. try { File file = new File ("MyFile.txt"); Scanner inputFile = new Scanner(file); } catch (FileNotFoundException e) { System.out.println("File not found."); } The Java Virtual Machine searches for a catch clause that can deal with the exception. Example: OpenFile.javaOpenFile.java

12-12 Handling Exceptions The parameter must be of a type that is compatible with the thrown exception’s type. After an exception, the program will continue execution at the point just past the catch block. Each exception object has a method named getMessage that can be used to retrieve the default error message for the exception. Example: ExceptionMessage.java ParseIntError.java

12-13 Polymorphic References To Exceptions A polymorphic reference can be used as a parameter in the catch clause. Most exceptions are derived from the Exception class. A catch clause that uses a parameter variable of the Exception type is capable of catching any exception that is derived from the Exception class. try { number = Integer.parseInt(str); } catch (Exception e){ System.out.println("The following error occurred: " + e.getMessage()); } The Integer class’s parseInt method throws a NumberFormatException object which is derived from the Exception class.

12-14 Handling Multiple Exceptions The code in the try block may be capable of throwing more than one type of exception. A catch clause needs to be written for each type of exception that could potentially be thrown. The JVM will run the first compatible catch clause found. The catch clauses must be listed from most specific to most general. Example: SalesReport.java, SalesReport2.javaSalesReport.javaSalesReport2.java

12-15 Exception Handlers There can be many polymorphic catch clauses. A try statement may have only one catch clause for each specific type of exception. try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) // ERROR!!! { System.out.println(str + " is not a number."); }

12-16 Exception Handlers The NumberFormatException class is derived from the IllegalArgumentException class. try { number = Integer.parseInt(str); } catch (IllegalArgumentException e) { System.out.println("Bad number format."); } catch (NumberFormatException e) // ERROR!!! { System.out.println(str + " is not a number."); }

12-17 Exception Handlers The previous code could be rewritten to work, as follows, with no errors: try { number = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println(str + " is not a number."); } catch (IllegalArgumentException e) //OK { System.out.println("Bad number format."); }

12-18 The finally Clause The try statement may have an optional finally clause. If present, the finally clause must appear after all of the catch clauses. try { (try block statements...) } catch (ExceptionType ParameterName) { (catch block statements...) } finally { (finally block statements...) }

12-19 The finally Clause The finally block is one or more statements, that are always executed after the try block has executed and after any catch blocks have executed if an exception was thrown. The statements in the finally block execute whether an exception occurs or not.

12-20 The Stack Trace The call stack is an internal list of all the methods that are currently executing. A stack trace is a list of all the methods in the call stack. It indicates: the method that was executing when an exception occurred and all of the methods that were called in order to execute that method. Example: StackTrace.javaStackTrace.java

12-21 Uncaught Exceptions When an exception is thrown, it cannot be ignored. It must be handled by the program, or by the default exception handler. When the code in a method throws an exception: normal execution of that method stops, and the JVM searches for a compatible exception handler inside the method. If there is no exception handler inside the method: control of the program is passed to the previous method in the call stack. If that method has no exception handler, then control is passed again, up the call stack, to the previous method. If control reaches the main method: the main method must either handle the exception, or the program is halted and the default exception handler handles the exception.

Tag in Documentation Comments General ExceptionName Description The following rules apply tag in a method’s documentation comment must appear after the general description of the method. The description can span several lines. It ends at the end of the documentation comment (the */ symbol) or at the beginning of another tag.