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.

Slides:



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

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.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
For use of Cleveland State's IST410 Students only 1 Exception.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Exceptions Exception. Exceptions Overview Exceptional Situations Syntax of Try, Catch, Throw Defining and Using Your Own Exceptions.
 It is possible to declare names for object references and not assign object references to them.  Such names literally refer to nothing at all.  It.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
1 Why do we need exceptions? In C, return variables must be used to indicate errors: if((fd = fopen(path,...)) == -1){ if(errno==a){...} else if(errno==b){...}
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class 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.
06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
©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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
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.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Exception Handling. Outline What is an Exception How to use exceptions catch ing throw ing Extending the Exception class Declaring using the throws clause.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exceptions Handling Exceptionally Sticky Problems.
JSP Exception Handling 20-Oct-15. JSP - E XCEPTION H ANDLING When you are writing JSP code, a programmer may leave a coding errors which can occur at.
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.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Introduction to Exceptions in Java CS201, SW Development Methods.
Java Exceptions a quick review….
Exceptions In this lecture:
Handling Exceptionally Sticky Problems
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exception Handling in Java
Handling Exceptionally Sticky Problems
Exceptions 10-May-19.
Java Basics Exception Handling.
CMSC 202 Exceptions.
Exception Handling.
Presentation transcript:

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 kinds of exceptions Today –How to write your own exceptions –Details of the exception classes –Why and when you should use exceptions –Some typical scenarios

Two Main Ideas Handling Exceptions Thrown by Someone Throwing Exceptions & Writing your own Exceptions Last Time Today

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

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

Why and when you should use exceptions If the method encounters a situation it can’t handle throw an exception Avoid using exceptions to indicate normal operations Use Design by Contract! –If a client calling a method has not fulfilled the contract throw a RuntimeException. –If your method is unable to fulfill its contract, throw either an Exception or RuntimeException. If you are throwing an exception for an abnormal condition that you feel client programmers should consciously decide how to handle, throw an Exception.

How to write your own exceptions Make a subclass of –Exception –Any existing exception Give it a name that represents what it is –class QueueEmptyException extends Exception –Build in extra functionality (if desired) You might want to do this just to give it a name of your choosing You might want to do this to add extra functionality like a static counter.

Scenarios You are writing a collection class and you are wondering how to handle the condition where the collection is empty but the bone- headed user* forgot to check. The demons running CENG217 have decided that you need to write your own exception or they’ll make you take the course over and over and over... You would like to see a fairly complex yet crystal clear example of exception usage *Might be you if it’s late enough!

You are writing a collection class and you are wondering how to handle the condition where the collection is empty but the bone-headed user forgot to check. // class Queue (continued) public Object dequeue() throws Exception { if(isEmpty()) throw new Exception (“Should check isEmpty() before dequeueing”); else // return the front object //... Note: We’re just throwing a plain old Exception

The demons running CENG 217 have decided that you need to write your own exception or they’ll make you take the course over and over and over... class QueueEmptyException extends Exception { public QueueEmptyException() {} public QueueEmptyException(String message) { super(message); } This should go in its own file: QueueEmptyException.java

Now we can use our own exception // class Queue (continued) public Object dequeue() throws QueueEmptyException { if(isEmpty()) throw new QueueEmptyException (“Should check isEmpty() before dequeueing”); else // return the front object //...

How do you use this queue? do { try { element = myQueue.dequeue(); } catch(QueueEmptyException qee) { System.out.println(“This can’t be happening!”); System.out.println(qee.getMessage()); } } while(! myQueue.isEmpty());

Note: You could choose to make this a RuntimeException class QueueEmptyException extends RuntimeException { public QueueEmptyException() {} public QueueEmptyException(String message) { super(message); }

In which case... // class Queue (continued) public Object dequeue() throws QueueEmptyException { if(isEmpty()) throw new QueueEmptyException (“Should check isEmpty() before dequeueing”); else // return the front object //...

How do you use this queue? while(! myQueue.isEmpty()) { element = myQueue.dequeue();. If an exception is thrown, the program will terminate. If an exception is thrown, the program will terminate.

You would like to see fairly complex yet crystal clear examples of exception usage public int getAge(int iSSN) throws RecordKeepingException { int index = getHashKey(iSSN); int iAge = myArray[index].getAge(iSSN); if (iAge <= 0) throw new RecordKeepingException (“Exception: Age for “ + iSSN + “ not in range: “ + iAge); else return iAge; } Home-grown!

You would like to see fairly complex yet crystal clear examples of exception usage public TreeNode getNodeRecursively(int index, TreeNode currentNode) throws MissingNodeException { if (currentNode == null) throw new MissingNodeException(); // Node not found! else if (currentNode.getNumber() == index) return currentNode; else if (currentNode.getNumber() > index) return getNodeRecursively (index, currentNode.getLeftChild()); else return getNodeRecursively (index, currentNode.getRightChild()); } // getNodeRecursively

You would like to see fairly complex yet crystal clear examples of exception usage public void initializeTreeNode(int iNumberNodes) { if (myTree == null) throw new NullPointerException (“Null tree found”); /* NOTE: Runtime exception; no need to declare propagation */ else for (int i=0; i < iNumberNodes; i++) { TreeNode newNode = new TreeNode( i ); myTree.insertNode(newNode); } } // initializeTreeNode

Lost Exceptions! class VeryImportantException extends Exception { public String toString() { return "A very important exception!"; } class HoHumException extends Exception { public String toString() { return "A trivial exception"; }

Lost Exceptions! public class LostMessage { void f() throws VeryImportantException { throw new VeryImportantException(); } void dispose() throws HoHumException { throw new HoHumException(); }

Lost Exceptions! // Still in classLostMessage public static void main(String[] args) throws Exception { LostMessage lm = new LostMessage(); try { lm.f(); } finally { lm.dispose(); }

Lost Exceptions! The output is: A trivial exception at LostMessage.dispose(LostMessage.java:21) at LostMessage.main(LostMessage.java:29)

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?

Be sure to Not overuse exceptions –Don’t use to indicate normal operations Not underuse exceptions –Design by Contract –Don’t ignore Catch exceptions Throw exceptions (Don’t have to!) Write your own exceptions (Don’t have to!)

Questions?