Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)

Slides:



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

Topics Introduction Types of Errors Exceptions Exception Handling
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
 Pearson Education, Inc. All rights reserved 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.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 16: Exception Handling.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
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.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
 2006 Pearson Education, Inc. All rights reserved Exception Handling.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
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.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Java Software Solutions Foundations of Program Design Sixth Edition
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.
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
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Java Programming: Guided Learning with Early Objects
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Lecture 18B Exception Handling and Richard Gesick.
Appendix H Exception Handling: A Deeper Look
Exception Handling in C++
16 Exception Handling.
Chapter 10 – Exception Handling
Exception Handling and Format output-CS1050-By Gayani Gupta
13 Exception Handling.
Chapter 14: Exception Handling
Presentation transcript:

Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)

Agenda Administrivia Class Static (Class, Methods, Variables) Exception Handling School of Information Systems & Technology2

Administrivia My name - Imroz Khan My - My AIM handle - imr 0 zkhan My office hours: Posted in the syllabus Any other time via appointment School of Information Systems & Technology3

4 Assignment Write a class that defines a Flight object which represents an airline flight. Be sure your class has the following: Variables to hold airline name, flight number, origin and destination cities. A static variable that keeps track of the total number of Flight objects that have been created. A constructor that accepts and initializes all class members. Getter and setter methods for each variable. A ToString method that will return a String representation of this flight. When you are finished writing your Flight class, create a driver file that will allow the user to enter as many Flights as they wish. When the user is finished entering data, print out the total number of flights entered and allow them to search the list of Flights by flight number or city. If the flight is found, display all information about that flight; otherwise display a message saying that this flight does not exist. The user should be able to search for as many flights as they wish. When the user is finished searching, the program should end.

5 Class In Java What is a class Template Model

6 Classes (Cont’d) Anatomy of a class Class provides one or more methods. Method represents task in a program Describes the mechanisms that actually perform its tasks Hides from its user the complex tasks that it performs Method call tells method to perform its task Classes contain one or more attributes Specified by instance variables Carried with the object as it is used Classes contain access modifier Public/Private/Default Object creation Static Non-static

7 Classes (Cont’d) Types of classes Regular Inner class Anonymous

8 Static Class Methods Variables

9 Exception Handling 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

10 Exception Handling Examples ArrayIndexOutOfBoundsException – an attempt is made to access an element past the end of an array ClassCastException – an attempt is made to cast an object that does not have an is-a relationship with the type specified in the cast operator NullPointerException – when a null reference is used where an object is expected

11 Exception Handling 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

12 Exception Handling With exception handling, the program catches and handles (i.e., deals with) the exception Next example allows user to try again if invalid input is entered (zero for denominator, or non-integer input)

13 Catching Exceptions 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 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

14 Termination Model of Exception Handling 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 statement – consists of try block and corresponding catch and/or finally blocks

15 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

16 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

17 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 Error s

18 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. 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

19 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

20 Finally Block Programs that obtain certain resources must return them explicitly to avoid resource leaks finally block Consists of finally keyword followed by a block of code enclosed in curly braces Optional in a try statement If present, is placed after the last catch block Executes whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks Will not execute if the application exits early from a try block via method System.exit Typically contains resource-release code

21 Finally Block If no exception occurs, catch blocks are skipped and control proceeds to finally block. After the finally block executes control proceeds to first statement after the finally block. If exception occurs in the try block, program skips rest of the try block. First matching the catch block executes and control proceeds to the finally block. If exception occurs and there are no matching catch blocks, control proceeds to the finally block. After the finally block executes, the program passes the exception to the next outer the try block. If catch block throws an exception, the finally block still executes.

22 Finally Block Standard streams System.out – standard output stream System.err – standard error stream System.err can be used to separate error output from regular output System.err.println and System.out.println display data to the command prompt by default

23 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

24 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

25 Getting log information 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

26 Questions?

27 Slides based on the presentations from Java How to Program Deitel Sun Microsystems Inc ( Credits