Data Structures. 02 Exception Handling

Similar documents
Exception Handling. Chapter 9

Exception Handling. Chapter 8. Chapter 8 1

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Comp 249 Programming Methodology Chapter 9 Exception Handling

ECE 122. Engineering Problem Solving with Java

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

BBM 102 Introduction to Programming II Spring Exceptions

Exceptions. CSC207 Winter 2017

Internal Classes and Exceptions

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

BBM 102 Introduction to Programming II Spring 2017

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Chapter 13 Exception Handling

EXCEPTION HANDLING. Summer 2018

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Chapter 8. Exception Handling

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Errors and Exceptions

Programming II (CS300)

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Sri Vidya College of Engineering & Technology Question Bank

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Chapter 12 Exception Handling

Exception Handling BASIC EXCEPTION HANDLING OBJECTIVES PREREQUISITES

Programming II (CS300)

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Program Correctness and Efficiency. Chapter 2

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

Exception-Handling Overview

Introduction to Software Design

CS159. Nathan Sprague

Object Oriented Programming

More on Exception Handling

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

More on Exception Handling

Exceptions and Libraries

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Java Errors and Exceptions. Because Murphy s Law never fails

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Chapter 3 Java Exception

Correctness and Robustness

CSCI 261 Computer Science II

14. Exception Handling

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Fundamentals of Object Oriented Programming

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

CSC 1214: Object-Oriented Programming

Lecture 19 Programming Exceptions CSE11 Fall 2013

CS 3 Introduction to Software Engineering. 3: Exceptions

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

Here is a hierarchy of classes to deal with Input and Output streams.

Motivations. Chapter 12 Exceptions and File Input/Output

CS 11 java track: lecture 3

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

CS 251 Intermediate Programming Exceptions

Exception Handling Advanced Programming Techniques

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

6.Introducing Classes 9. Exceptions

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Exceptions. What exceptional things might our programs run in to?

Writing your own Exceptions. How to extend Exception

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS112 Lecture: Exceptions and Assertions

Chapter 14. Exception Handling and Event Handling


CS 209 Programming in Java #10 Exception Handling

CS159. Nathan Sprague

Exceptions. Examples of code which shows the syntax and all that

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Chapter 14. Exception Handling and Event Handling ISBN

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

Chapter 14. Exception Handling and Event Handling 异常处理和事件处理. 孟小亮 Xiaoliang MENG, 答疑 ISBN

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

EXCEPTIONS. Java Programming

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Chapter 11 Handling Exceptions and Events. Chapter Objectives

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

Java for Programmers Course (equivalent to SL 275) 36 Contact Hours

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

COMP1008 Exceptions. Runtime Error

Exceptions - Example. Exceptions - Example

Introduction Unit 4: Input, output and exceptions

For more details on SUN Certifications, visit

CS Programming I: Exceptions

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Std 12 Lesson-10 Exception Handling in Java ( 1

Exception Handling: Control. Exception handling is the control of error conditions or other unusual events during the execution of a program.

CMSC 202. Exceptions

Transcription:

David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ. All Rights Reserved

Objectives q Describe the notion of exception handling q React correctly when certain exceptions occur q Use Java's exception-handling facilities effectively in classes and programs q Create & use custom exceptions 2

What is an Exception? q The term exception is shorthand for the phrase "exceptional event." q Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. q When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. q Creating an exception object and handing it to the runtime system is called throwing an exception. 3

What is an Exception? q After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack (see the next figure). 4

The Call Stack 5

Basic Exception Handling 6

Exceptions in Java q An exception is an object n Signals the occurrence of unusual event during program execution q Throwing an exception n Creating the exception object q Handling the exception n Code that detects and deals with the exception 7

Exceptions in Java q Consider a program to assure us of a sufficient supply of milk q Possible solution, class GotMilk (next slide) Sample screen output 8

9

Exceptions in Java q Now we revise the program to use exceptionhandling q View new version, class ExceptionDemo Sample screen output 1 Sample screen output 2 10

try block catch block 11

Exceptions in Java q Note try block n Contains code where something could possibly go wrong n If it does go wrong, we throw an exception q Note catch block n When exception thrown, catch block begins execution n Similar to method with parameter n Parameter is the thrown object 12

Predefined Exception Classes q Java has predefined exception classes within Java Class Library n You can place method invocation in try block n You follow with catch block for this type of exception q Example classes n NullPointerException n ArrayIndexOutOfBoundsException n ClassNotFoundException n IOException n NoSuchMethodException 13

Predefined Exception Classes q Example code 14

More About Exception Classes 15

Outline q Declaring Exceptions (Passing the Buck) q Kinds of Exceptions q Errors q Multiple Throws and Catches q The finally Block q Rethrowing an Exception q Case Study : Custom Exceptions 16

Declaring Exceptions q Consider a method where its code throws an exception n May want to handle immediately n May want to delay until something else is done q Method that does not catch an exception n Notify programmers (users) of your method with throws clause n Programmer then given responsibility to handle exception 17

Declaring Exceptions q Note syntax for throws clause q Note distinction n Keyword throw used to throw exception n Keyword throws used in method header to declare an exception 18

Declaring Exceptions q If a method throws an exception and the exception is not caught inside the method n Method ends immediately after exception thrown q A throws clause in overriding method n Can declare fewer exceptions than declared n But not more q View program example, class DoDivision 19

20

21

22

Kinds of Exceptions q In most cases, exception is caught either. n In a catch block or n Be declared in a throws clause q But Java has exceptions you do not need to account for q Categories of exceptions n Checked exceptions n Unchecked exceptions 23

Kinds of Exceptions q Checked exception n Must be caught in a catch block n Or declared in a throws clause q Unchecked exception n Also called run-time n Need not be caught in catch block or declared in throws n However, exceptions that highlight coding problems should be fixed (obviously ) 24

Checked Exceptions q Exceptions checked by compiler n Need to be handled in the code as Compiler gives a compile error if they are not handled n Exceptions are thrown by methods that are used in the code w That s how Compiler recognizes them q What happens when exceptions are caught depends on the exception handling strategy n Exception handling code defines how exceptions are handled q Examples - The JDBC API & File I/O 25

Unchecked Exceptions q Exceptions that are thrown by the Java Virtual Machine n Cannot be handled at the compilation as compiler does not enforce developers to handle exceptions n These exceptions occur at the runtime n Hard to catch specific unchecked exception as they are not checked by the compiler n Example Basic I/O, Numbers Vs Text (look at the Scanner class.), Attempt to use array index out of bounds, Division by zero 26

Exception Hierarchy Checked, enforced by Compiler Throwable Exception Error RuntimeException Unchecked, thrown by JVM 27

Exception Hierarchy q Throwable top of the exception hierarchy in Java, all exceptions are of this type q Error represents serious problems in program, that usually cannot be recovered from; thrown by the JVM (see next slide) q Exception superclass for all exceptions including user-defined exceptions q RuntimeException also thrown by JVM and caused by illegal operations 28

Some Common Java Errors q NoSuchMethodError n Application calls method that no longer exist in the class definition w Usually happens if class definition changes at runtime q NoClassDefFoundError n JVM tries to load class and class cannot be found w Usually happens if classpath is not set, or class somehow gets removed from the classpath q ClassFormatError n JVM tries to load class from file that is incorrect w Usually happens if class file is corrupted, or if it isn t class file 29

Multiple Throws and Catches q A try block can throw any number of exceptions of different types q Each catch block can catch exceptions of only one type n Order of catch blocks matter! why?? q View example program, class TwoCatchesDemo 30

try block custom exceptions catch blocks 31

Multiple Throws and Catches q Note multiple sample runs Sample screen output 1 Sample screen output 2 Sample screen output 3 32

Multiple Throws and Catches q Exceptions can deal with invalid (as apposed to incorrect) user input q Use of the throw statement should be reserved for cases where it is unavoidable q Convention suggests separate methods for throwing and catching of exceptions q Nested try-catch blocks rarely useful 33

The finally Block q Possible to add a finally block after sequence of catch blocks q Code in finally block executed n Whether or not execution thrown n Whether or not required catch exists 34

The finally block q Executes always at the end after the last catch block (if one exists) n Commonly used for cleaning up resources (closing files, streams, etc.) public void mymethod() { try{ //code that throws exception e1 //code that throws exception e2 } catch (MyException e1){ //code that handles exception e1 } catch (Exception e2){ //code that handles exception e2 } finally{ //clean up code, close resources } } 35

Defining Your Own Exception Classes 36

Defining Your Own Exception Classes q Must be derived class of some predefined exception class n Convention suggests use classes derived from class Exception q View sample class class DivideByZeroException and q View demo program class DivideByZeroDemo 37

Extend from Exception Two constructors 38

39

40

41

Defining Your Own Exception Classes q Different runs of the program Sample screen output 1 Sample screen output 2 Sample screen output 3 42

Defining Your Own Exception Classes q Note method getmessage defined in exception classes n Returns string passed as argument to constructor n If no actual parameter used, default message returned q The type of an object is the name of the exception class 43

Defining Your Own Exception Classes Guidelines q Use the Exception as the base class q Define at least one, but preferably two, constructors n Default, no parameter n With String parameter q Start constructor definition with call to constructor of base class, using super q No need to override inherited getmessage 44

Graphics Supplement 45

Graphics Supplement: Outline q Exceptions in GUIs q Programming Example: a JFrame GUI Using Exceptions 46

Exceptions in GUIs q Not good practice to use throws clauses in the methods n In JFrame GUI or applet, uncaught exception does not end the program n However GUI may not cope correctly, user may receive sufficient instructions q Thus most important to handle all checked exceptions correctly 47

Programming Example q A JFrame GUI using exceptions q View GUI class class ColorDemo q Note exception class class UnknownColorException q View driver program class ShowColorDemo 48

49

Programming Example 50

Summary q An exception is an object derived from class Exception n Descendants of class Error behave like exceptions q Exception handling allows design of normal cases separate from exceptional situations q Two kinds of exceptions n Checked and unchecked 51

Summary q Exceptions can be thrown by n Java statements n Methods from class libraries n Programmer use of throw statement q Method that might throw but not catch an exception should use throws clause q Exception is caught in catch block 52

Summary q A try block followed by one or more catch blocks n More specific exception catch types should come first q Every exception type has getmessage method usable to recover description of caught description q Do not overuse exceptions 53

Portion of Throwable hierarchy Throwable Exception Error Runtime Exception IOException AWTError ThreadDeath OutOf MemoryError ArrayIndexOutOfBoundsException InputMismatchException ClassCastException NullPointerException ArithmeticException 54

Questions? 55