Exceptions Lecture 11 COMP 401, Fall 2014 9/25/2014.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exceptions1 Syntax, semantics, and pragmatics. Exceptions2 Syntax, semantics, pragmatics Syntax –How it looks, i.e. how we have to program to satisfy.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
11-Jun-15 Exceptions. 2 Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
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.
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
Exceptions Handling the unexpected. RHS – SWC 2 The Real World So far, most of our code has been somewhat näive We have assumed that nothing goes wrong…
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.
Exceptions, cont’d. Factory Design Pattern COMP 401 Fall 2014 Lecture 12 9/30/2014.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
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.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Eighth Lecture Exception Handling in Java
Java Exceptions a quick review….
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Exceptions 10-Nov-18.
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
CSE 143 Java Exceptions 1/18/2019.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling.
Presentation transcript:

Exceptions Lecture 11 COMP 401, Fall /25/2014

Exception Handling What is an exception? – Unexpected (or at least unusual or abnormal) – Disruptive – Possibly fatal 2

Before exception handling... Strategy 1: Global Error Code – Well-documented global variable – Set to some sort of code when something goes wrong. – Onus on programmer to check the code when appropriate. – lec11.ex1 3

Before exception handling... Strategy 2: Special return value. – Specific return value(s) that are interpreted as errors. – Common conventions: Procedures (i.e., does not produce a result) – 0 indicates success (i.e., no error) – Less than zero indicates some type of error. – Mapping of values to types of error documented with procedure. Functions (i.e., expected to produce a value) – If reference type is expected, then null signals error. – If value type is expected, choose some “out of domain” value to signal an error. – lec11.ex2

Drawbacks to ad-hoc approaches Inconsistent May not have an “out-of-domain” value to use to signal error condition. Puts onus on programmer to properly detect and handle return value as an error. Limited information about the error. Difficult to extend in future development.

Exception Handling Formal mechanism for detecting and dealing with exceptions – Most modern OO languages provide it. Java, C++, C#, Python, Ruby, etc. Two parts: – Throwing Signaling that an exception has occurred. Also known as “raising” an exception. – Catching Handling an exception when it occurs.

Benefits of Exception Handling Promotes good software engineering. – Consistency – Modularity – Separation of concerns – Extensibility Provides an abstraction hierarchy for error information. – Information about when and why the error occurred is encapsulated into an object. Improves code organization – Separates error handling code from “normal” code. – Provides a facility for ensuring that critical code executes no matter what happens.

Exception Handling in Java Two kinds of exceptions: – Checked exceptions Possibly valid situations that system should have some way of dealing with. Examples: – Trying to open a file that doesn’t exist. – Reading past the end of a file. – The printer is out of ink. – Unchecked exceptions Also known as “runtime” exceptions. Exceptions that should never happen and usually indicate a bug or flaw in logic. – Out of bounds indexing of an array. – Illegal cast of an object reference. 8

Runtime Exceptions To signal a runtime exception… – Create a RuntimeException object and then “throw” it. Constructor accepts a string message. – Usually done on the same line. Default behavior is to end program and print information about the exception to the console. lec11.ex3

Catching Exceptions May not want the program to end. – May be able to recover or otherwise deal with the problem. try-catch blocks – Put code that might generate the exception inside a “try” block. – Follow try block with one or more “catch” blocks. – Each catch block is associated with a specific exception type and declares a variable that is set to the exception object if that type of exception is raised. Exception object has methods to get information about the error. lec11.ex4

Extending RuntimeException You can create your own runtime exception types by subclassing from runtime exception. Allows you to encapsulate custom information about the exception. lec11.ex5

Catching more than one Can specify different catch blocks for different types of exceptions. – An exception matches the first catch block with a declared exception variable that has an “is-a” relationship with the raised exception. lec11.ex6

The finally block Sometime we need some code to run no matter what happens. – Often this is the case in order to free up some system resource such as closing a file or closing a network connection. finally block will execute no matter what happens (exception or no). lec11.ex7

The Throwable Class Hierarchy Throwable – Superclass for all objects that can be “thrown” Error – Superclass for errors generally caused by external conditions. Exception – Superclass for exceptions generally caused by internal conditions.

Checked vs. Unchecked Error, RuntimeException, and their subclasses are “unchecked” exceptions. All other subclasses of Exception are “checked”.

Checked Exceptions Checked exceptions are subject to the “catch or specify” rule. – A method that could potentially throw a checked exception must declare the possibility as part of its method signature. – A method that calls another method that throws a checked exception must either: Catch: Include code that catches the exception. Specify: Declare the possibility of the exception as part of its own method signature. Why? – Forces user of method to explicitly handle the exception or pass the buck to whomever calls it. – Enforces good error handling. lec11.ex8

General Principle: Be Specific Use an existing exception type. – There are lots. – If semantics of the exception match well, then go ahead and use it. Create your own exception type. – Subclass either RuntimeException or Exception lec11.ex9.v1 – Notice how less specific general exception raised by Scanner transformed into context-specific exception for Playlist. – Also note how error message can be retrieved from exception object. See handling of PlaylistFormatError in main() See reference page for Exception for more. 17

General Principle: Catch Late Exceptions should rise to level where application has enough context to deal with them effectively. – Catching exception just because you can is not always the right thing to do. Pass the buck unless response to this exception under all or nearly all circumstances is well-understood at this point. – Look again at lec11.ex9.v1 In particular, note handling of FileNotFoundException – lec11.ex9.v2 Note printStackTrace() method of Exception in Main1 Note differences in how FileNotFoundException handled in Main1 vs. Main2 – Main1 not even given the chance because handled by playlist. – Main2 has ability to re-prompt for new filename and does so. 18

General Principle: Throw Early Validate values as early as possible. – Rather than waiting for exception generated by invalid values sent to other code. Particularly apropos for null values that may later cause a NullPointerException Exception generated by null pointer is not very specific Almost always have to look higher in the stack trace to see what the real problem is. lec11.ex9.v3 – Changed how Main2 reads filename in order to demonstrate this point. 19

Odds and Ends Remember that the scope of a variable is limited to the surrounding block. – Sometimes an issue if you declare a variable inside a try block but then need its value outside of the try block later. Sibling catch blocks can reuse the same variable name for the declared error object. A catch block associated with an exception class cannot precede a catch block associated with a subclass. – Results in unreachable code. try-catch-finally blocks can be nested. Interfaces must declare any checked exceptions thrown by any of its implementations. Finally always runs – Even if you “return” from within a try or catch block – lec11.ex10