Exceptions Part I. Old Stuff To perform division one must first press a small button on the carriage which indicates where the decimal point should.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Yoshi
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
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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
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.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
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.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
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.
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
©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.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
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.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Object Oriented Programming
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
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.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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.
Chapter 8-Exception Handling/ Robust Programming.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
Exceptions Part II. What you need to know Last time –What happens when an exception is thrown –What are your choices for handling exceptions –The different.
Exceptions 10-Nov-18.
Web Design & Development Lecture 7
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exception Handling Contents
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Exception Handling.
Presentation transcript:

Exceptions Part I

Old Stuff

To perform division one must first press a small button on the carriage which indicates where the decimal point should be situated in the quotient(bölüm). Then, the dividend(bölünen) is entered on the big keyboard, and the "ENTER DIVD" button is pressed. This shifts the carriage over to the position indicated for the decimal point, and enters the dividend into the accumulator. Then, the keyboard is cleared (if the "ADD" key is on, the keyboard clears automatically, however, if it is off, the keyboard must be cleared manually with the "K B CLEAR" key), and the divisor(bölen) entered into the big keyboard. Then, BOTH divide keys are depressed simultaneously, and the machine begins a process of shifting the carriage to the right to find a point where the divisor can start to be subtracted from the dividend. Once that point is found, then successive subtractions of the divisor occur until an overdraft (IE: the accumulator goes negative) occurs, and each subtraction is counted in the counter register. A single addition of the divisor corrects for the overdraft, and then the carriage shifts to the left, and the process repeats until the quotient is left in the counter register, and the remainder is left in the accumulator. From the manual:

/435 = ?

Slight problem If division by zero is attempted the calculator just keeps trying to subtract and never stops. Very exciting! Okay for a machine with an operator but what about an automatic machine? Need to take action upon encountering certain error conditions like “division by zero” Architecture modified to detect error conditions and branch to handler code. So how do we handle the situation?

Early Approaches to Errors Basic ONERROR GOTO 100 C ch = getchar(); /* ch will be set equal to EOF on end of file */

Basic Problems Programmers never think they will make errors Programmers are wrong a lot! Want to make code robust(sağlam) Want to force users to maintain robustness Need a “clean” way of handling problems

Solutions? Could have methods return a value that tells us whether or not we had an error? –Then can’t return anything else or –Have to return a composite object Even with some kind of error code –Does it give us enough information? –Does it give us flexibility –Does it include a way to make sure we check it?

Exceptions--Traditional Methods if (someMethod( ) == true) { if (someOtherMethod( ) == true) { if (someThirdMethod( ) == true) { // no errors; do intended actions } else { // handle error caused by someThirdMethod( ) } else { // handle some error caused by someOtherMethod( ) } else { // handle some error caused by someMethod( ) }

How would we use?…. Exceptions--Global Variables Another way to deal with error handling is to have the value of a global variable represent the error. int iErrorValue = 0; public void someMethod( ) { // do someMethod’s stuff here // if there is an error, then set iErrorValue = 1 } public void someOtherMethod( ) { // do someOtherMethod’s stuff here // if there is an error, then set iErrorValue = 2 } public void someThirdMethod( ) { // do someThirdMethod’s stuff here // if there is an error, then set iErrorValue = 3 }

continued Exceptions--Global Variables public void doIt() { someMethod(); someOtherMethod(); someLastMethod(); if (iErrorValue == 1)... if (iErrorValue == 2)... if (iErrorValue == 3)... } But: What if the run-time error stopped us from continuing? For example: What if someMethod( ) failed in such a way that we cannot go on to someOtherMethod( )? To cope, we find ourselves with code that’s nearly as messy as the earlier example which featured multiple nested-ifs:

public void doit( ) { someMethod( ); if (iErrorValue == 1) /* Handle Error 1 here */ else { someOtherMethod( ); if (iErrorValue == 2) /* handle Error 2 here */ else { someThirdMethod( ); if (iErrorValue == 3) /* Handle Error 3 here */ else { /* do intended actions here */ } // else } // doit Note: with this technique we potentially must wrap the ENTIRE program in a series of if/else clauses, duplicating code in places. (Do we prefer robustness or clarity/maintainability?) Exceptions--Global Variables Don’t write code like this!

Solution Exceptions Java uses termination model of exception handling:program control cannot return directly to the throw point –resumption model of exception handling: control would return to thepoint at which the exception occurred and resume execution. Exceptions are thrown –like an NFL referee throws a penalty flag Exceptions can be thrown by Java (Today) Exceptions can be thrown by you! (Next Time)

What you need to know Today –What happens when an exception is thrown –What are your choices for handling exceptions –The different kinds of exceptions Next Time –How to write your own exceptions –Details of the classes –Why and when you should use exceptions –Some typical scenarios

Two Main Ideas Handling Exceptions thrown by someone else Throwing Exceptions & writing your own Exceptions Today Next Time

What happens when an exception is thrown? An exception object is created (on the heap) The current “context” is halted/aborted Execution starts in some error handling code –Can be in current method –Can be external to current method The error handling code has access to the exception object which can be used to –Access a String message contained in the exception –Determine what type of exception was thrown –Print a stack trace –Other cool stuff (like rethrow the exception, increment a counter, etc.)

What are your choices for handling exceptions Handle in current method try { /* Code that might throw an exception */ } catch (ExceptionType ) { /* Code that handles exception */ } Handle outside current method void someMethod() throws Exception { } void someMethod throws AnotherException { } More details on this later! More details on this later!

The different kinds of exceptions Error –For the big guys Exception –The “standard” exception –Java enforces handling –An unusual condition RuntimeException –e.g. classCast Exception –Can indicate using a class improperly –No special handling

15.4 Java Exception Hierarchy Superclass Throwable –Subclass Exception Exceptional situations Should be caught by program –Subclass Error Typically not caught by program Checked exceptions –Catch or declare Unchecked exceptions

Inheritance hierarchy for class Throwable Throwable ExceptionError AWTErrorThreadDeathIOExceptionRuntimeExceptionOutOfMemoryError

Details of the classes Object ErrorException RuntimeException Throwable others... getMessage printStackTrace toString IOException

15.8 printStackTrace, getStackTrace and getMessage Throwable class –Method printStackTrace Prints method call stack –Method getStackTrace Obtains stack-trace information –Method getMessage Returns descriptive string

Nitty Gritty A method which throws an exception must explicitly “announce” this fact (compiler enforced) in the method header throw clause public void someMethod() throws SomeException UNLESS The exception is a RuntimeException (or a child of RuntimeException) OR The exception is handled inside the method

Here’s the idea If you as a developer write a class with a method that throws an exception then Java forces all users of the class to deal with it. This is unlike earlier programming languages where there was no way to insure that programmers properly handled error conditions. Again we try to deal with problems at compile time as opposed to runtime

But what about RuntimeExceptions? Certain types of exceptions can occur in almost every method and including code for these conditions would be burdensome Runtime Exception Examples: –ArithmeticException –ClassCastException –EmptyStackException –IllegalArgumentException –IndexOutOfBoundsException –UnsupportedOperationException –NegativeArraySizeException –NoSuchElementException –NullPointerException So no special note must be made in method headers. So no special note must be made in method headers. And it doesn’t have to be handled. Program can be allowed to terminate.

Handle Them Yourself! One or more statements that might throw an exception are placed in a try block The try block is followed by one or more catch blocks catch(IOException ioe) { /* Code to handle IOException here e.g.:*/ System.out.println(ioe.getMessage()); } catch(Exception e) { /* Code to handle other exceptions here */ } Put the subclasses before the classes

15.6 finally Clause Resource leak –Caused when resources are not released by a program The finally block –Appears after catch blocks –Always executes –Use to release resources

Finally In certain cases (no matter what) it is desirable to have some code that will be executed after the try block. (Like closing a file or a network connection). This means whether or not exceptions were encountered. The solution is the finally block try {} catch(Ex1 e) {} catch(Ex2 e) {} finally { /* Code that will execute! */ } Don’t pack up your books yet!

Scenario You are trying to use a method that throws an exception. The compiler is complaining. It’s late.

class SomeClass {... public void someMethod(...) {... BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); inbuf = stdin.readLine();... }... } C:>javac SomeClass.java SomeClass:299: Exception java.io.IOException must be caught, or it must be declared in the throws clause of this method. inbuf = stdin.readLine(); ^ 1 error

Check the API... readLine public String readLine() throws IOException Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line- termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs

You are trying to use a method that throws an exception. The compiler is complaining. It’s late. BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); try { inbuf = stdin.readLine(); } catch (IOException ioe) { System.out.println("Oh, darn!"); } Java requires you to somehow handle the exception. It doesn’t require you to do anything smart.

You are trying to use a method that throws an exception. The compiler is complaining. It’s late. class SomeClass {... public void someMethod(...) throws IOException {... BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); inbuf = stdin.readLine();... }... } Or you could just add throws IOException to the method header Or you could just add throws IOException to the method header

You are trying to use a method that throws an exception. The compiler is complaining. It’s late. class SomeClass {... public void someMethod(...) throws IOException {... BufferedReader stdin = new BufferedReader( new InputStreamReader(System.in)); inbuf = stdin.readLine();... }... // Someplace else someReference.someMethod() // Now this line is a problem!!! } Of course, if you use this technique you still need to deal with the problem! Of course, if you use this technique you still need to deal with the problem!

Print an error message Log the exception Retry the method (maybe with default parameters) Restore the system to some previously known "good" state. Set the system to some "safe" state. Let exception propagate to whoever called the method in which the exception arose Catch it and ignore it “Catch it and ignore it” is generally bad: If the error was serious enough to throw an exception, it should be dealt with, not ignored. When Catching Exceptions you can... OOA/OOD/OOP “Who” knows enough to handle the exception? local? high-level?

Questions?