HST 952 Computing for Biomedical Scientists Lecture 7.

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

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.
1 Week 11 l Basic Exception Handling »the mechanics of exceptions l Defining and Using Exceptions »some "simple" cases l Reality Check »guidelines for.
COMP 121 Week 5: Exceptions and Exception Handling.
Copyright © 2008 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
Exception Handling Chapter 8. Outline Basic Exception Handling Defining Exception Classes Using Exception Classes.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Class Hierarchy (Inheritance)
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 8 l Basic Exception Handling »the mechanics of exceptions l.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
COMP201 Java Programming Topic 6: Exceptions Reading: Chapter 11.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. Chapter 16 Exception Handling.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
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.
Slides prepared by Rose Williams, Binghamton University Chapter 9 Exception Handling.
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.
Chapter 8Java: an Introduction to Computer Science & Programming - Walter Savitch Announcements l Project 6 now out. »Milestone due Oct. 24th »Final project.
Chapter 81 Exception Handling Chapter 8. 2 Reminders Project 5 due Oct 10:30 pm Project 3 regrades due by midnight tonight Discussion groups now.
©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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
Java Exception Handling
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.
COMP 103 Comparators and Comparable. RECAP  Iterator and Iterable TODAY  Comparator and Comparable  Exceptions 2 RECAP-TODAY.
Chapter 81 Exception Handling Chapter 8. 2 Objectives become familiar with the notion of exception handling learn Java syntax for exception handling learn.
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.
Exception Handling Exceptions and language features to handle them.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Object Oriented Programming
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
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.
Java Programming: Guided Learning with Early Objects
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Computer Programming with JAVA Chapter 8. Exception Handling Basic Exception Handling the mechanics of exceptions Defining and Using Exceptions some "simple"
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Chapter 8-Exception Handling/ Robust Programming.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Lecturer: Dr. AJ Bieszczad Chapter 8 COMP 150: Introduction to Object-Oriented Programming 8-1 l Basic Exception Handling »the mechanics of exceptions.
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.
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.
Chapter 14 – Exception Handling
Announcements/Reminders
Exception Handling Chapter 9.
Exception Handling Chapter 8 Basic Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Exceptions 10-May-19.
Coming up Exceptions An Example The Throws keyword Try and Catch
Exception Handling Chapter 8 Basic Exception Handling
CMSC 202 Exceptions.
Presentation transcript:

HST 952 Computing for Biomedical Scientists Lecture 7

Outline Information hiding revisited Intro to exceptions in java Programming examples

Information Hiding Revisited To achieve information hiding goal, need to make a class’s instance variables private and provide public accessor methods for retrieving and setting these variables’ values For instance variables that have a class type, this may not be enough! Variables with primitive types in Java are passed or returned by value –a copy of the variable’s value is passed/returned, the original contents of the variable cannot be modified by changing this copy

Information Hiding Revisited In general, class variables are passed or returned by reference –a copy of the memory address the variable refers to is passed, the contents of this memory address can be altered once this address is known (Exceptions to this rule in Java are variables of the String and StringBuffer classes which act like variables of primitive types when passed/returned)

Information Hiding Revisited –cloning a variable is one solution to this problem –a clone has the same contents as the original variable but a different address in memory –altering the clone does not affect the original –classes that allow cloning implement the cloneable interface (e.g. GregorianCalendar) –some classes do not allow cloning (do not implement the cloneable interface) e.g. String, StringBuffer

Information Hiding Revisited Programming example

Exceptions: Overview Exceptions give us a way of organizing a program into sections for the normal case and the exceptional case –exception examples: division by zero incorrect type of input Simplifies development, testing, debugging and maintenance –errors are easier to isolate

Exceptions: Some Terminology Throwing an exception: either Java itself or your code signals that something unusual has happened Handling an exception: responding to an exception by executing a part of the program specifically written for the exception –also called catching an exception

Exceptions: Some Terminology The normal case is handled in a try block The exceptional case is handled in a catch block The catch block takes a parameter of type Exception –it is called the catch -block parameter Exception is a built-in Java class If an exception is thrown execution in the try block ends and control passes to the catch block(s) after the try block

try-throw-catch Threesome Basic code organization : try { if(test condition) throw new Exception("Message to display"); } catch(Exception e) { } Programming example: restricting the length of an input string

Try block Statements execute up to the conditional throw statement If the condition is true the exception is thrown –control passes immediately to the catch block(s) after the try block Else the condition is false –the exception is not thrown –the remaining statements in the try block (those following the conditional throw) are executed try-throw-catch Threesome

Catch block Executes if an exception is thrown –may terminate execution with exit statement –if it does not exit, execution resumes after the catch block Statements after the Catch block Executed if either the exception is not thrown or if it is thrown but the catch block does not exit the program try-throw-catch Threesome

More about the catch-Block Although it may look similar to a method definition The catch -block is not a method definition! Every Exception has a getMessage method –it retrieves the string given to the exception object when it was thrown, e.g. throw new Exception("This message is retrieved"); A catch -block applies only to an immediately preceding try block –if no exception is thrown the catch block is ignored

Predefined Exception Classes Exception is the root class of all exceptions Many predefined classes throw exceptions –the documentation or interface will tell you –the exceptions thrown are often also predefined Some common predefined exceptions: –IOException –ClassNotFoundException, and –FileNotFoundException

Documentation for Exception class java.lang Class Exception java.lang.Object | +--java.lang.Throwable | +--java.lang.Exception All Implemented Interfaces: Serializable The package which Exception belongs to Ancestor class for all Java classes Sub-class of Object Sub-class of Throwable Taken from A Java class cannot be a subclass of more than one class, but sometimes we need it to have properties of more than one class. To get around this, Java allows a class to implement more than one interface. An interface is a property of a class that says what methods it must have.

Documentation for Exception class Direct Known Subclasses: AclNotFoundException, ActivationException, AlreadyBoundException, ApplicationException, AWTException, BadLocationException, ClassNotFoundException, CloneNotSupportedException, DataFormatException, ExpandVetoException, FontFormatException, GeneralSecurityException, IllegalAccessException, InstantiationException, InterruptedException, IntrospectionException, InvalidMidiDataException, InvocationTargetException, IOException, LastOwnerException, LineUnavailableException, MidiUnavailableException, MimeTypeParseException, NamingException, NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException, NotBoundException, NotOwnerException, ParseException, PrinterException, PrivilegedActionException, PropertyVetoException, RemarshalException, RuntimeException, ServerNotActiveException, SQLException, TooManyListenersException, UnsupportedAudioFileException, UnsupportedFlavorException, UnsupportedLookAndFeelException, UserException

Documentation for Exception class public class Exception extends Throwable The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. Constructor Summary: Exception() Constructs an Exception with no specified detail message. Exception(String s) Constructs an Exception with the specified detail message.

Documentation for Exception class Methods inherited from class java.lang.Throwable: fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait Constructor Detail public Exception() Constructs an Exception with no specified detail message. public Exception(String s) Constructs an Exception with the specified detail message. Parameters: s - the detail message.

Using an Object that May Throw an Exception Sample object = new SampleClass(); try { object.doStuff();//may throw IOException } catch(IOException e) { System.out.println(e.getMessage()); } Predefined exceptions usually include a meaningful message that is retrieved with getMessage

User-Defined Exception Classes Must be derived from some already defined exception class Often the only method you need to define is the constructor Include a constructor that takes a String message argument Also include a default constructor with a call to super and default message string public class DivideByZeroException extends Exception { public DivideByZeroException() { super("Dividing by Zero!"); } public DivideByZeroException(String message) { super(message); }

When to Define Your Own Exception Class When you use a throw -statement in your code you should usually define your own exception class. If you use a predefined, more general exception class, then your catch -block will have to be general. A general catch -block could also catch exceptions that should be handled somewhere else. A specific catch -block for your own exception class will catch the exceptions it should and pass others on (e.g., DivideByZeroException will only catch divisions by zero and will ignore NumberFormatExceptions)

Example: Using the Divide- ByZero- Exception Class public double divide(int numerator, int denominator) { double quotient = SENTINEL; try { if (denominator == 0) throw new DivideByZeroException(); quotient = numerator/(double)denominator; System.out.println(numerator + "/" + denominator + " = " + quotient); } catch(DivideByZeroException e) { System.out.println(e.getMessage()); } return(quotient); }

Catching an Exception in a Method other than the One that Throws It When defining a method you must include a throws -clause to declare any exception that might be thrown but is not caught in the method. Use a throws -clause to "pass the buck" to whatever method calls it (pass the responsibility for the catch block to the method that calls it) –that method can also pass the buck, but eventually some method must catch it This tells other methods "If you call me, you must handle any exceptions that I throw."

Example: throws-Clause divide method May throw a DivideByZeroException in another method normal that calls it But the catch block is in main So normal must include a throws -clause in the first line of the method definition: public void normal() throws DivideByZeroException { }

More about Passing the Buck Good programming practice: Every exception thrown should eventually be caught in some method Normally exceptions are either caught in a catch block or deferred to the calling method in a throws -clause If a method throws an exception, it expects the catch block to be in that method unless it is deferred by a throws -clause –if the calling method also defers with a throws -clause, its calling program is expected to have the catch block, etc., up the line all the way to main, until a catch block is found

Uncaught Exceptions In any one method you can catch some exceptions and defer others If an exception condition occurs but the exception is not caught in the method that throws it or any of its calling methods, either: –the program ends abnormally, or, –in the case of a GUI using Swing, the program may become unstable

throws-Clauses in Derived Classes You cannot add exceptions to the throws -clause of a redefined method in a derived class –only exceptions in the throws -clause of the parent class's method can be in the throws -clause of the redefined method in the derived class In other words, you cannot throw any exceptions that are not either caught in a catch block or already listed in the throws -clause of the same method in the base class You can, however, declare fewer exceptions in the throws - clause of the redefined method

Multiple Exceptions and catch Blocks in a Method Methods can throw more than one exception The catch blocks immediately following the try block are searched in sequence for one that catches the exception type –the first catch block that handles the exception type is the only one that executes Specific exceptions are derived from more general types –both the specific and general types from which they are derived will handle exceptions of the more specific type So put the catch blocks for the more specific, derived, exceptions early and the more general ones later

Exception: Reality Check Exception handling can be overdone –use it sparingly and only in certain ways If the way an exceptional condition is handled depends on how and where the method is invoked, then it is better to use exception handling and let the programmer handle the exception (by writing the catch block and choosing where to put it) Otherwise it is better to avoid throwing exceptions

The finally Block At this stage of your programming you may not have much use for the finally block, but it is included for completeness - you may find it useful in the future You can add a finally block after the try / catch blocks finally blocks execute whether or not catch block(s) execute Code organization using finally block: try block catch block finally { }

Three Possibilities for a try-catch- finally Block The try -block runs to the end and no exception is thrown. –The finally -block runs after the try -block. An exception is thrown in the try -block and caught in the matching catch -block. –The finally -block runs after the catch -block. An exception is thrown in the try -block and there is no matching catch -block. –The finally -block is executed before the method ends. –Code that is after the catch -blocks but not in a finally - block would not be executed in this situation.

An exception is an object descended from the Exception class Exception handling allows you to design code for the normal case separately from that for the exceptional case You can use predefined exception classes or define your own Exceptions can be thrown by: –certain Java statements –methods from class libraries –explicit use of the throw statement An exception can be thrown in either –a try block, or –a method definition without a try block, but in this case the call to the method must be placed inside a try block Summary

An exception is caught in a catch block When a method might throw an exception but does not have a catch block to catch it, usually the exception class must be listed in the throws -clause for the method A try block may be followed by more than one catch block –more than one catch block may be capable of handling the exception –the first catch block that can handle the exception is the only one that executes –so put the most specific catch blocks first and the most general last Every exception class has a getMessage method to retrieve a text message description of the exception caught

Before Next Class Read Chapter 9 and Section 10.1

Programming examples Exceptions (divide by zero)

Questionnaire