Exceptions Exception. Exceptions Overview Exceptional Situations Syntax of Try, Catch, Throw Defining and Using Your Own Exceptions.

Slides:



Advertisements
Similar presentations
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Advertisements

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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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 Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
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.
Exception handling Dealing with life’s little surprises.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
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
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.
VB.Net - Exceptions Copyright © Martin Schray
COMP Exception Handling Yi Hong June 10, 2015.
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.
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.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Data Structures and Java CS /14/2015 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved. L6:
Exceptions and Assertions Chapter 15 – CSCI 1302.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
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.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
Chapter 10 – Exception Handling
Java Programming Language
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exception Handling Chapter 9 Edited by JJ.
Exceptions 25-Apr-19.
Exceptions 22-Apr-19.
Exceptions 10-May-19.
Exceptions 5-Jul-19.
Presentation transcript:

Exceptions Exception

Exceptions Overview Exceptional Situations Syntax of Try, Catch, Throw Defining and Using Your Own Exceptions

Exceptional Situations Exceptions model atypical situations –errors in computation or data –invalid method parameters –failure to complete task Exceptions provide the programmer with information regarding problems –ex, NullPointerException s indicate an action on null reference –some must be handled, others do not (next slide) Can handle exceptions by catching them –respond to exceptions usefully –see how to do this in a few slides... Exceptions allow a method to delegate to caller (method that called the one throwing the exception) how the exception is to be handled

Exception s are classes that extend Throwable –come in two types: those that must be handled somehow (well see how soon), such as IOException – e.g., an issue reading a file those that do not; e.g., RuntimeException s such as NullPointerException Error s (far less common, FYI only) –could be indirectly caused by your code (such as using up all available memory); could be entirely unrelated –you should not attempt to handle these Exceptional Situations in Java

Exception Handling Syntax (1/2) Until now, you have had no control over coping with exceptions. With a catch statement, you have the chance to implement your own exception handling Process for handling exceptions –try some code, catch exception thrown by tried code, finally, “clean up” if necessary –try, catch, and finally are reserved words try denotes code that may throw an exception –place questionable code within a try block –a try block must be immediately followed by a catch block unlike an if w/o else –thus, try-catch blocks always occurs as pairs catch exception thrown in try block and write special code to handle it –catch blocks distinguished by type of exception –can have several catch blocks, each specifying a particular type of exception –Once an exception is handled, execution continues after the catch block finally (optional) –special block of code that is executed whether or not an exception is thrown –follows catch block

All parts enclosed in curly braces {} try block comes first catch block comes after try –put exception in parentheses as in method definition –you can also have multiple catch blocks –formal parameter of type java.lang.Exception is the most general and would catch all exceptions (because they are all subclasses) finally block always comes last Here’s the basic syntax: // Somewhere in your program… try { // Code “in question” } catch (most_specific_exception_type name) { // Code in response to exception }... finally { // Code guaranteed to be executed after try // (and previous catches) } Exception Handling Syntax (2/2)

Exception Handling Example 1 A method call within a try block may set off a chain of method calls, the last of which throws an exception –Andy tells Wendy to getADrink() ; Wendy tells Sam to getADrink(). Sam is asleep and throws a DrinkNotAvailableException which is defined elsewhere –This exception is not a subclass of RuntimeException, so it should be caught) public class Andy { // Properties, constructor, methods //to teach, kayak, eat Chinese food, //etc. elided ;) public void getWater() { try { // getADrink() might throw a //DrinkNotAvailableException so //we have to put it in a try block _water = _wendy.getADrink(); } catch(DrinkNotAvailableException e){ this.fire(_wendy); }

Exception Handling Example 2 try-catch blocks can be nested! –If Andy’s call to Wendy to getADrink() throws DrinkNotAvailableException, he can ask Michelle to getADrink(). Exception Resolution –similar to method resolution in inheritance hierarchies: starts with the method that throws exception –work back up the chain of method calls until a try - catch block is found for that exception (or a superclass of that exception) so, you do not necessarily have to try and catch every exception at every level of calling if an exception must be caught, then you’d better be sure that you catch the exception at some point! if exception is not caught, program will crash or not perform as expected public class Andy { // other code elided public void getWater() { try { _water = _wendy.getADrink(); } catch (DrinkNotAvailableException e) { this.fire(_wendy); try { _water = _michelle.getADrink(); } catch(DrinkNotAvailableException e){ this.fire(_michelle); }

Defining Your Own Exceptions You can define and throw your own specialized exceptions: throw new DataOutOfBoundsException(…); throw new QueueEmptyException(…); Useful for responding to special cases, not covered by pre-defined exceptions –you can throw an exception for a different class to catch –a method of error handling For example: public class DataOutOfBoundsException extends Exception { public DataOutOfBoundsException(String dataName){ super(“Data value ” + dataName + “ is out of bounds.”); } } The class Exception has a method getMessage().The String passed to super is printed to the output window for debugging when getMessage() is called by the user

Using Your Own Exceptions (1/2) Every method that throws Exception s that are not subclasses of RuntimeException must declare what exceptions it throws in method declaration setAge() is throwing the exception, and we’ll see in the next slide that the exception will be caught in the method that calls setAge() // Defined in the Person class public void setAge(int age) throws DataOutOfBoundsException { if (age 120){ throw new DataOutOfBoundsException(age+“”); } // age+“”: converts age from int to //String //Note the constructor takes in a //String for message printing _age = age; }

Using Your Own Exceptions (2/2) Method that calls setAge() should have a try block surrounding the method call and an accompanying catch block to handle DataOutOfBoundsException public void clonePerson() { Person clone = new Person(); int random = (int)(Math.random() * 1000); try { clone.setAge(random); } catch (DataOutOfBoundsException e) { System.out.println(e.getMessage()); // gets the message describing // the exception that occurred }

QueueEmptyException Create your own QueueEmptyException : –Subclass RuntimeException, so that every time dequeue() is called, we don’t need to surround it with a try - catch block – same idea behind ArrayIndexOutOfBoundsException –If the exception indicates an actual problem, then don’t catch it! It should halt the execution of the program public class QueueEmptyException extends RuntimeException { public QueueEmptyException() { super(“Queue is empty”); } public class Queue { // QueueEmptyException is a // RuntimeException, so we don’t need //to write “throws” in the method // declaration public Type dequeue() { if (this.isEmpty()){ throw new QueueEmptyException(); } //Remaining dequeue() code goes here }

Exceptions: Pros and Cons Pros: –cleaner code: rather than returning a boolean up chain of calls to check for exceptional cases, throw an exception! –use return value for meaningful data, not error checking –factor out error-checking code into one class, so it can be reused Cons: –throwing exceptions requires extra computation –can become messy if not used sparingly –can accidentally cover up serious exceptions, such as NullPointerException by catching them

In conclusion Words of Wisdom: –Never try to “fix up” your program by catching all exceptions “Oh… NullPointerException … let me just catch it, so the TAs won’t know I have buggy code! Hahahaha!!!” –Best to throw an exception when an error occurs that you cannot deal with yourself, but can be better handled by some method on the stack Wow, what an Exception -al lecture!