An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
©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.
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.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
COMP 121 Week 5: Exceptions and Exception Handling.
© 2004 Pearson Addison-Wesley. All rights reserved10-1 Chapter 10 : Exceptions Intermediate Java Programming Summer 2007.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
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.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Chapter Chapter 8 Exceptions and Assertions.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
Microsoft VB 2005: Reloaded, Advanced Chapter 5 Input Validation, Error Handling, and Exception Handling.
ITEC200 Week02 Program Correctness and Efficiency.
Program Correctness and Efficiency Chapter 2. Chapter 2: Program Correctness and Efficiency2 Chapter Objectives To understand the differences between.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
©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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
Program Correctness and Efficiency Chapter 2. Chapter Objectives  To understand the differences between the three categories of program errors  To understand.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exceptions and Assertions Animated Version.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
Java Software Solutions Foundations of Program Design Sixth Edition
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
1 Chapter Eight Exception Handling. 2 Objectives Learn about exceptions and the Exception class How to purposely generate a SystemException Learn about.
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
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Introduction to Exception Handling and Defensive Programming.
Chapter 14: Exception Handling. Objectives In this chapter, you will: – Learn what an exception is – Learn how to handle exceptions within a program –
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Exceptions and Assertions Chapter 15 – CSCI 1302.
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
DCS 2133 Object Oriented Programming ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Exception Handling.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
16 Exception Handling.
Chapter 14: Exception Handling
Advanced Programming Behnam Hatami Fall 2017.
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Presentation transcript:

An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions

Objectives In this chapter you will: Explore how Java throws and catches exceptions Become familiar with many of Java’s exception classes Take a first look at the concept of inheritance Write code that handles exceptions thrown by a Java program Create assertions to debug a program

Exceptions and Assertions Applications should be robust, or well constructed Applications should be fault tolerant, or forgiving of user mistakes Compile-time errors are violations of the programming language syntax Runtime errors occur during program execution and can cause a program to crash Logic errors produce incorrect output

Exception Handling Runtime errors are referred to as exceptions When Java creates an exception object, it throws the exception for further processing Two ways to handle exceptions  Do nothing: Let the Java runtime system handle it  Write additional code to handle the exception Handling the exception is preferable

An Example of a Thrown Exception The error message produced by Java when an exception is thrown is the stack trace The method-call stack is the sequence of method calls that leads to creation of exception

An Example of a Thrown Exception (continued)

The exception was created in Line 48 of NumberFormatException.java The method-call stack steps through each call to a method, originating in Line 15 of main The stack trace gives a complete description of the NumberFormatException object One option is to add logic to allow the user to enter a greater variety of input

An Example of a Thrown Exception (continued) When an exception is thrown, the Java runtime system looks for code to handle the exception The method-call stack is checked for this code If no such code exists, the exception object is printed and the program terminates If the exception were handled by the programmer, the code could exit more gracefully The user could correct mistakes before the program exited

Handling Errors with Program Logic User input can be checked for validity using additional logic As programs become more complex, handling errors with additional logic becomes more complicated Adding logic may make the program less readable Adding logic may make the program more difficult to maintain

Handling Exceptions with the try Statement Catching exceptions allows for customized error statements The user can correct mistakes without restarting the program The programmer needs three tools  The try block  The catch block  The finally block

Handling Exceptions with the try Statement (continued) A try block begins with the keyword try  Contains statements where exceptions originate  Contains statements that should normally execute If an exception occurs, the rest of the try block is skipped If an exception occurs, program control goes to the first catch block following the try block

Handling Exceptions with the try Statement (continued) For each try block there is one or more catch blocks There is one catch block for each type of exception thrown A catch block begins with the keyword catch and the exception parameter in parentheses When an exception is thrown, if a catch block matches the exception type, it is executed

Handling Exceptions with the try Statement (continued) After the catch block is executed, program control continues after the last catch block An uncaught exception is handled by the Java runtime system  The object’s stack trace is displayed  The program terminates If no exceptions are thrown, the program skips all catch and finally blocks and processing continues normally

Handling Exceptions with the try Statement (continued) The finally block is a set of statements that always executes  Useful for tasks like closing files A try statement is the try, catch and finally blocks e is the customary identifier for an exception object

Handling Exceptions with the try Statement (continued) try statement syntax: try { normal program statements } catch (TypeOfException_1 e) { statements to process this exception } … catch (Type of Exception_n e) { statements to process this exception } finally { statements that always execute }

Handling Exceptions with the try Statement (continued) If a try statement is added to a program, a catch statement must also be added Each catch statement handles one type of exception A catch block executes only if an exception of the specified type is thrown within the try block A finally block can be added immediately after a try block or a combination of try and catch blocks

Classifying Exceptions Exceptions can be classified according to an inheritance hierarchy Exceptions can be classified as checked or unchecked An inheritance hierarchy is like a taxonomy, a classification scheme according to common and unique characteristics A subclass inherits from the class above it A superclass is above a subclass

Classifying Exceptions (continued)

An unchecked exception inherits from the RuntimeException class All other exception classes are checked Checked exceptions cause compiler errors if they are not handled Unchecked exceptions do not cause compile- time errors, but may cause runtime errors A throws clause follows the method declaration throws TypeOfException1,TypeOfException2…

Multiple Catch Blocks and Programmer-Defined Exceptions The types of exceptions that can be thrown are discovered through extensive testing catch blocks must immediately follow try blocks with no intervening code A catch block for a more specific type of exception should precede more general types Can use an IllegalArgumentException for exception types not previously defined in Java An Exception object can also be used, but it is poor programming practice

Propagating Exceptions An exception propagator is a method that originates an exception An exception catcher is the method that catches the exception If an exception originates in a method but is not caught, the exception propagates up the method-call stack The method-call stack is the sequence of method calls

Propagating Exceptions (continued)

Apply the Concept The application divides two numbers, and is simple to showcase exception handling A boolean flag thereIsAnError signals that an error or exception has occurred Three methods are called in a while loop  getDividend  getDivisor  calculateAndDisplay The while loop executes while thereIsAnError is true

Apply the Concept (continued) Exceptions are caught if the user terminates the application prematurely Exceptions are caught if the user enters letters instead of digits Exceptions originating in getDividend and getDivisor propagate to main The method calculateAndDisplay catches an IllegalArgumentException if the divisor is zero

Apply the Concept (continued)

Assertions Three major types of errors  Compile-time errors  Runtime errors  Logic errors Compile-time errors are the result of syntax errors Runtime errors cause the program to terminate while running Logic errors cause incorrect output

Using an Assertion An assertion is designed to help the programmer detect logic errors The syntax of an assert statement: assert expression : error message The expression is a boolean expression that should always be true if the program is working The error message is displayed if the expression ever becomes false Assertions are placed after all values in expression have been determined

An Example of an Assertion An assert statement is placed to verify that kilograms are less than pounds If the assertion is false, an AssertionError is thrown The custom error is optional, but useful Compile with the –source 1.5 option Run with assertions enabled: -ea

An Example of an Assertion (continued)

Summary Programs can be made more robust and fault tolerant using exception handling Exceptions are handled using a try statement The try statement consists of a try block, a catch block, and an optional finally block Exceptions can be classified according to the inheritance hierarchy, or as checked or unchecked The inheritance hierarchy is a taxonomy of Java classes

Summary (continued) A subclass inherits from the class just above it The superclass is the class just above a given class in the hierarchy Unchecked exceptions inherit from the RuntimeException class All other exceptions are checked Checked exceptions must be handled or the program will not compile

Summary (continued) Must be one catch block for every try block Each catch block handles one type of exception Multiple catch blocks may follow a try block Exceptions that are not caught are propagated up the method-call stack An assertion can be used to guarantee that programmers don’t make major logic errors