Exception Handling and Format output-CS1050-By Gayani Gupta

Slides:



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

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 8 Exceptions and Assertions.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 2006 Pearson Education, Inc. All rights reserved. Exception Handling in C++ CS-2303, C-Term Exception Handling in C++ CS-2303 System Programming.
Exception Handling and Format output
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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 More Exception Handling and Throwing Exceptions.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Chapter Chapter 8 Exceptions and Assertions.
C++ Exception Handling
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions Handling.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
Exception Handling and Format output. Midterm exam Date: Nov 1 st, 2006 Content: Week 1 to Week 8 Format: Multiple choice Determine the results of the.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
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.
Chapter 12: Exception Handling
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Exception Handling in C++. Outline What exceptions are and when to use them Using try, catch and throw to detect, handle and indicate exceptions, respectively.
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.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Appendix H Exception Handling: A Deeper Look
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Exception Handling in C++
16 Exception Handling.
Chapter 10 – Exception Handling
Chapter 13 Exception Handling
Why exception handling in C++?
COMPSCI 230 S Programming Techniques
13 Exception Handling.
Chapter 14: Exception Handling
Chapter 6-3 (Book Chapter 8)
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Chapter 12: Exceptions and Advanced File I/O
Lecture 11 Objectives Learn what an exception is.
Chapter 6-3 (Book Chapter 8)
Exceptions 10-May-19.
CMSC 202 Exceptions.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exception Handling and Format output-CS1050-By Gayani Gupta

Introduction Exception – an indication of a problem that occurs during a program’s execution Exception handling – resolving exceptions that may occur so program can continue or terminate gracefully Exception handling enables programmers to create programs that are more robust and fault-tolerant

Introduction Examples ArrayIndexOutOfBoundsException – an attempt is made to access an element past the end of an array NullPointerException – when a null reference is used where an object is expected

Exception-Handling Overview Intermixing program logic with error-handling logic can make programs difficult to read, modify, maintain and debug Exception handling enables programmers to remove error-handling code from the “main line” of the program’s execution Improves clarity Enhances modifiability

Example: Not Catching Exceptions String inputStr; int age; inputStr = JOptionPane.showInputDialog(null, "Age:"); age = Integer.parseInt(inputStr); Error message for invalid input Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException. Exception in thread "main" java.lang.NumberFormatException: For input string: "ten" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at Week7.SimpleException.main(SimpleException.java:12)

Catching an Exception try catch inputStr = JOptionPane.showInputDialog(null, "Age:"); try { age = Integer.parseInt(inputStr); } catch (NumberFormatException e){ JOptionPane.showMessageDialog(null, "’" + inputStr + "‘ is invalid\n" + "Please enter digits only"); } try catch This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.

Performance Tip If the potential problems occur infrequently, intermixing program and error-handling logic can degrade a program’s performance, because the program must perform (potentially frequent) tests to determine whether the task executed correctly and the next task can be performed.

Try-catch: what does that mean? When an exception occurs, or is thrown, the normal sequence of flow is terminated. The exception-handling routine is then executed; we say the thrown exception is caught.

Try-catch: what does that mean? try block – encloses code that might throw an exception and the code that should not execute if an exception occurs Consists of keyword try followed by a block of code enclosed in curly braces

Try-catch: what does that mean? catch block – catches (i.e., receives) and handles an exception, contains: Begins with keyword catch Exception parameter in parentheses – exception parameter identifies the exception type and enables catch block to interact with caught exception object Block of code in curly braces that executes when exception of proper type occurs

Try-catch: what does that mean? Matching catch block – the type of the exception parameter matches the thrown exception type exactly or is a superclass of it Uncaught exception – an exception that occurs for which there are no matching catch blocks Cause program to terminate if program has only one thread; Otherwise only current thread is terminated and there may be adverse effects to the rest of the program

try-catch Control Flow This illustrates how the control flows when there is an exception and when there is no exception. In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.

try-catch Control Flow When an exception occurs: try block terminates immediately Program control transfers to first matching catch block After exception is handled: Termination model of exception handling – program control does not return to the throw point because the try block has expired; Flow of control proceeds to the first statement after the last catch block Resumption model of exception handling – program control resumes just after throw point

try-catch Control Flow try statement – consists of try block and corresponding catch and/or finally blocks Logic errors can occur if you assume that after an exception is handled, control will return to the first statement after the throw point.

Tip With exception handling, a program can continue executing (rather than terminating) after dealing with a problem. This helps ensure the kind of robust applications that contribute to what is called mission-critical computing or business-critical computing.

Review To catch an exception, code must be enclosed in a a. throws block. b. catch block. c. try block. d. finally block.

Review To catch an exception, code must be enclosed in a a. throws block. b. catch block. c. try block. d. finally block.

Review An uncaught exception: a. is a possible exception that never actually occurs during the execution of the program. b. is an exception that occurs for which the matching catch clause is empty. c. is an exception that occurs for which there are no matching catch clauses. d. is another term for a thrown exception

Review An uncaught exception: a. is a possible exception that never actually occurs during the execution of the program. b. is an exception that occurs for which the matching catch clause is empty. c. is an exception that occurs for which there are no matching catch clauses. d. is another term for a thrown exception

Getting Information There are two methods we can call to get information about the thrown exception: getMessage printStackTrace try { . . . } catch (NumberFormatException e){ System.out.println(e.getMessage()); e.printStackTrace(); } In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.

printStackTrace, getStackTrace and getMessage Methods in class Throwable retrieve more information about an exception printStackTrace – outputs stack trace to standard error stream getStackTrace – retrieves stack trace information as an array of StackTraceElement objects; enables custom processing of the exception information getMessage – returns the descriptive string stored in an exception

Multiple catch Blocks A single try-catch statement can include multiple catch blocks, one for each type of exception. try { . . . age = Integer.parseInt(inputStr); // Asuming I have a file I/O here } catch (NumberFormatException e){ } catch (FileNotFoundException file_error){ } In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.

Multiple catch Control Flow Here's how the control flows when there are multiple catch blocks. In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.

The finally Block There are situations where we need to take certain actions regardless of whether an exception is thrown or not. We place statements that must be executed regardless of exceptions in the finally block. The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.

try-catch-finally Control Flow Here's how the control flows when there are multiple catch blocks and the finally block. In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement. If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.

Propagating Exceptions Instead of catching a thrown exception by using the try-catch statement, we can propagate the thrown exception back to the caller of our method. The method header includes the reserved word throws. public int getAge( ) throws NumberFormatException { . . . int age = Integer.parseInt(inputStr); return age; } Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.

Throwing Exceptions We can write a method that throws an exception directly, i.e., this method is the origin of the exception. Use the throw reserved to create a new instance of the Exception or its subclasses. The method header includes the reserved word throws. public void doWork(int num) throws Exception { . . . if (num != val) throw new Exception("Invalid val"); } It is possible to throw an exception from our own method.

Sample Call Sequence This illustration shows a sequence of method calls among the exception throwers. Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher. The call sequence is traced by using a stack.

Exception Thrower When a method may throw an exception, either directly or indirectly, we call the method an exception thrower. Every exception thrower must be one of two types: catcher. propagator. We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.

Review Which of the following is not true regarding the throw point of an exception? a. It specifies the point at which the exception must be handled. b. It is the initial point at which the exception occurs. c. It is specified as the top row of the method-call stack at the time the exception occurred. d. All of the above statements are true.

Review Which of the following is not true regarding the throw point of an exception? a. It specifies the point at which the exception must be handled. b. It is the initial point at which the exception occurs. c. It is specified as the top row of the method-call stack at the time the exception occurred. d. All of the above statements are true.

Review Which of the following is not true regarding the throw point of an exception? a. It specifies the point at which the exception must be handled. b. It is the initial point at which the exception occurs. c. It is specified as the top row of the method-call stack at the time the exception occurred. d. All of the above statements are true.

Review question Which of the following statements is not true? a. Exception handling enables programmers to write robust and fault-tolerant programs. b. Exception handling can only catch the exception but cannot resolve the exception. c. Exception handling can resolve exceptions. d. The Java 2 Platform, Standard Edition, Version 1.4 introduced the new chained exception feature.

Review question Which of the following statements is not true? a. Exception handling enables programmers to write robust and fault-tolerant programs. b. Exception handling can only catch the exception but cannot resolve the exception. c. Exception handling can resolve exceptions. d. The Java 2 Platform, Standard Edition, Version 1.4 introduced the new chained exception feature.

Debugging 101 execute your Java program line by line examine the value of variables at different points in the program How to do: set a breakpoint in your code so the debugger suspends execution (double-click in the gray margin on the left side of the editor ) choose Run -> Debug As -> Java Applications

Types of Exception Throwers An exception catcher is an exception thrower that includes a matching catch block for the thrown exception. An exception propagator does not contain a matching catch block. A method may be a catcher of one exception and a propagator of another.

Using the throws Clause throws clause – specifies the exceptions a method may throws Appears after method’s parameter list and before the method’s body Contains a comma-separated list of exceptions Exceptions can be thrown by statements in method’s body of by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses

When to Use Exception Handling Exception handling designed to process synchronous errors Synchronous errors – occur when a statement executes Asynchronous errors – occur in parallel with and independent of the program’s flow of control

Java Exception Hierarchy All exceptions inherit either directly or indirectly from class Exception Exception classes form an inheritance hierarchy that can be extended Class Throwable, superclass of Exception Only Throwable objects can be used with the exception-handling mechanism Has two subclasses: Exception and Error Class Exception and its subclasses represent exception situations that can occur in a Java program and that can be caught by the application Class Error and its subclasses represent abnormal situations that could happen in the JVM – it is usually not possible for a program to recover from Errors

Portion of class Throwable’s inheritance hierarchy.

Checked/Compiling vs. Unchecked/Running time There are two types of exceptions: Checked/Compiling time Unchecked/Run time A checked exception is an exception that is checked at compile time. All other exceptions are unchecked, or runtime, exceptions. As the name suggests, they are detected only at runtime.

Different Handling Rules When calling a method that can throw checked exceptions use the try-catch statement and place the call in the try block, or modify the method header to include the appropriate throws clause. When calling a method that can throw runtime exceptions, it is optional to use the try-catch statement or modify the method header to include a throws clause.

Handling Checked/Compiling Exceptions Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.

Handling Unchecked/Runtime Exceptions It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.

Java Exception Hierarchy Two categories of exceptions: checked and unchecked Checked exceptions Exceptions that inherit from class Exception but not from RuntimeException Compiler enforces a catch-or-declare requirement Compiler checks each method call and method declaration to determine whether the method throws checked exceptions. If so, the compiler ensures that the checked exception is caught or is declared in a throws clause. If not caught or declared, compiler error occurs.

Java Exception Hierarchy Unchecked exceptions Inherit from class RuntimeException or class Error Compiler does not check code to see if exception is caught or declared If an unchecked exception occurs and is not caught, the program terminates or runs with unexpected results Can typically be prevented by proper coding

Java Exception Hierarchy catch block catches all exceptions of its type and subclasses of its type If there are multiple catch blocks that match a particular exception type, only the first matching catch block executes It makes sense to use a catch block of a superclass when all the catch blocks for that class’s subclasses will perform the same functionality

Outline

Review Exceptions can occur: a. from the Java Virtual Machine. b. through explicitly mentioned code in a try block. c. through calls to other methods made in a try block. d. All of the above.

Review Exceptions can occur: a. from the Java Virtual Machine. b. through explicitly mentioned code in a try block. c. through calls to other methods made in a try block. d. All of the above.

Review In the catch block below, what is nullPointerException? catch (NullPointerException nullPointerException ) { System.err.println(“nullPointerException”); } // end catch a. The type of the exception being caught. b. The name of catch block’s exception parameter. c. A finally block. d. An exception handler.

Review In the catch block below, what is nullPointerException? catch (NullPointerException nullPointerException ) { System.err.println(“nullPointerException”); } // end catch a. The type of the exception being caught. b. The name of catch block’s exception parameter. c. A finally block. d. An exception handler.

Throwing Exceptions Using the throw Statement throw statement – used to throw exceptions Programmers can thrown exceptions themselves from a method if something has gone wrong throw statement consists of keyword throw followed by the exception object

Rethrowing Exceptions Exceptions are rethrown when a catch block decides either that it cannot process the exception or that it can only partially process it Exception is deferred to outer try statement Exception is rethrown by using keyword throw followed by a reference to the exception object

Stack Unwinding Stack unwinding – When an exception is thrown but not caught in a particular scope, the method-call stack is “unwound,” and an attempt is made to catch the exception in the next outer try block.

Stack Unwinding When unwinding occurs: The method in which the exception was not caught terminates All local variables in that method go out of scope Control returns to the statement that originally invoked the method – if a try block encloses the method call, an attempt is made to catch the exception.

Declaring New Exception Types You can declare your own exception classes that are specific to the problems that can occur when another program uses your reusable classes New exception class must extend an existing exception class

Declaring New Exception Types Typically contains only two constructors One takes no arguments, passes a default exception messages to the superclass constructor One that receives a customized exception message as a string and passes it to the superclass constructor