CMSC 202. Exceptions II

Similar documents
CS 111 Classes I 1. Software Organization View to this point:

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

D06 PROGRAMMING with JAVA. Ch3 Implementing Classes

Lecture J - Exceptions

D06 PROGRAMMING with JAVA

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Basics of Java Programming Input and the Scanner class

Inheritance, overloading and overriding

What are exceptions? Bad things happen occasionally

CS193j, Stanford Handout #10 OOP 3

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Software Construction

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

More on Objects and Classes

Install Java Development Kit (JDK) 1.8

Java: overview by example

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Java Programming Language

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Introduction to Java

Chapter 13 - Inheritance

Introduction to Object-Oriented Programming

Java Interview Questions and Answers

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Explain the relationship between a class and an object. Which is general and which is specific?

Object-Oriented Programming in Java

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

AP Computer Science Java Subset

public static void main(string[] args) { System.out.println("hello, world"); } }

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Moving from CS 61A Scheme to CS 61B Java

CS506 Web Design and Development Solved Online Quiz No. 01

CISC 181 Project 3 Designing Classes for Bank Accounts

C++ INTERVIEW QUESTIONS

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

AP Computer Science File Input with Scanner

Java CPD (I) Frans Coenen Department of Computer Science

Arrays in Java. Working with Arrays

Lecture 5: Java Fundamentals III

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

D06 PROGRAMMING with JAVA

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Course Intro Instructor Intro Java Intro, Continued

6.1. Example: A Tip Calculator 6-1

Chapter 2 Introduction to Java programming

Crash Course in Java

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

CMSC 202H. ArrayList, Multidimensional Arrays

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Chapter 5 Names, Bindings, Type Checking, and Scopes

Part I. Multiple Choice Questions (2 points each):

An Incomplete C++ Primer. University of Wyoming MA 5310

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Fundamentals of Java Programming

public void creditaccount(string accountnumber, float amount) { this.accounts.get(accountnumber).credit(amount); }

Data Flow Static Code Analysis Best Practices

Introduction to Programming System Design. CSCI 455x (4 Units)

Chapter 1 Java Program Design and Development

CSCI 253. Object Oriented Programming (OOP) Overview. George Blankenship 1. Object Oriented Design: Java Review OOP George Blankenship.

Comp 248 Introduction to Programming

RMI Client Application Programming Interface

CPLEX Tutorial Handout

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

No no-argument constructor. No default constructor found

Event-Driven Programming

Introduction to Programming

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

The C Programming Language course syllabus associate level

Description of Class Mutation Mutation Operators for Java

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

Getting Started with the Internet Communications Engine

Building Java Programs

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Computing Concepts with Java Essentials

Java from a C perspective. Plan

Using Files as Input/Output in Java 5.0 Applications

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

AP Computer Science Java Mr. Clausen Program 9A, 9B

Hoare-Style Monitors for Java

Chapter 2 Elementary Programming

Basic Object-Oriented Programming in Java

Assignment 4 Solutions

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Transcription:

CMSC 202 Exceptions II

Methods may fail for multiple reasons public void withdraw(double amount){ if(amount < 0) throw new Exception("Amount Negative"); if(amount > balance) throw new IllegalArgumentException("Overdraft of" + amount); balance -= amount; Withdraw can fail in multiple ways. Each is its own exceptional event and should be handled differently. Overdraft's usually incur a penalty against your account until you have move money around accordingly. 11/2010 2

Multiple catch Blocks A try block can call a method that potentially throws any number of exception values, and they can be of differing types In any one execution of a try block, at most one exception can be thrown (since a throw statement ends the execution of the try block) However, different types of exception values can be thrown on different executions of the try block 3

Multiple catch Blocks Each catch block can only catch values of the exception class type given in the catch block heading Different types of exceptions can be caught by placing more than one catch block after a try block Any number of catch blocks can be included, but they must be placed in the correct order 4

Multiple catch Blocks public void main(string[] args){ BankAccount account = new BankAccount(100.00); Scanner input = new Scanner(System.in); System.out.print("Enter deposit amount: "); int amt = input.nextint(); try{ account.withdraw(amt); catch (IllegalArgumentException e){ // code that "handles" the overdraft exception catch (Exception e){ // code that "handles" the negative exception 11/2010 5

Catch the More Specific Exception First When catching multiple exceptions, the order of the catch blocks is important When an exception is thrown in a try block, the catch blocks are examined in order The first one that matches the type of the exception thrown is the one that is executed 6

Catch the More Specific Exception First public void main(string[] args){ BankAccount account = new BankAccount(100.00); Scanner input = new Scanner(System.in); System.out.print("Enter withdraw amount: "); int amt = input.nextint(); try{ account.withdraw(amt); catch (Exception e){ // problems // code that "handles" the negative exception catch (IllegalArgumentException e){ // code that "handles" the overdraft exception 7

Catch the More Specific Exception First Because a DepositNegativeException and DepositTooSmallException are types of Exception, all exceptions will be caught by the first catch block before ever reaching the second or third block The catch blocks for DepositNegativeException and DepositTooSmallException will never be used! For the correct ordering, simply put the catch block for Exception last. 11/2010 8

Defining Exception Classes A throw statement can throw an exception object of any exception class Instead of using a predefined class, exception classes can be programmer-defined These can be tailored to carry the precise kinds of information needed in the catch block A different type of exception can be defined to identify each different exceptional situation 9

Defining Exception Classes Every exception class to be defined must be a derived class of some already defined exception class It can be a derived class of any exception class in the standard Java libraries, or of any programmer defined exception class Constructors are the most important members to define in an exception class They must behave appropriately with respect to the variables and methods inherited from the base class Often, there are no other members, except those inherited from the base class The following exception class performs these basic tasks only 10

Exception Object Characteristics The two most important things about an exception object are its type (exception class) and the message it carries The message is sent along with the exception object as an instance variable This message can be recovered with the accessor method getmessage, so that the catch block can use the message 11

Programmer-Defined Exception Class Guidelines Exception classes may be programmer-defined, but every such class must be a derived class of an already existing exception class The class Exception can be used as the base class, unless another exception class would be more suitable At least two constructors should be defined, sometimes more The exception class should allow for the fact that the method getmessage is inherited 12

Preserve getmessage For all predefined exception classes, getmessage returns the string that is passed to its constructor as an argument Or it will return a default string if no argument is used with the constructor This behavior must be preserved in all programmer-defined exception class A constructor must be included having a string parameter whose body begins with a call to super The call to super must use the parameter as its argument A no-argument constructor must also be included whose body begins with a call to super This call to super must use a default string as its argument 13

A Programmer-Defined Exception Class 14

Tip: An Exception Class Can Carry a Message of Any Type: double Message An exception class constructor can be defined that takes an argument of another type It would stores its value in an instance variable It would need to define accessor methods for this instance variable A programmer defined exception class may include any information that might be helpful to the recipient 11/2010 15

An Exception Class with an double Message public class InvalidAmountException extends Exception { private double amount; public InvalidAmountException(double amount){ super("invalid Amount Exception: $" + amount); this.amount = amount; public double getamount(){ return amount; 11/2010 16

Declaring Exceptions in a throws Clause If a method can throw an exception but does not catch it, it must provide a warning This warning is called a throws clause The process of including an exception class in a throws clause is called declaring the exception throws AnException //throws clause public int deposit( int amt ) throws DepositNegativeException, DepositTooSmallException { if (amt < 0 ) throw new DepositNegativeException( ); if (amt < mindeposit) throw new DepositTooSmallException( ); balance += deposit; 17

Checked and Unchecked Exceptions Exceptions that are subject to the catch or declare rule are called checked exceptions The compiler checks to see if they are accounted for with either a catch block or a throws clause The classes Throwable, Exception, and all descendants of the class Exception are checked exceptions All other exceptions are unchecked exceptions The class Error and all its descendant classes are called error classes Error classes are not subject to the Catch or Declare Rule 18

Exceptions to the Catch or Declare Rule Checked exceptions must follow the Catch or Declare Rule Programs in which these exceptions can be thrown will not compile until they are handled properly Unchecked exceptions are exempt from the Catch or Declare Rule Programs in which these exceptions are thrown simply need to be corrected, as they result from some sort of error 11/2010 All rights reserved 19

Hierarchy of Throwable Objects 20

Runtime Exceptions Runtime exceptions are Unchecked Frequently thrown by Java automatically when there is a bug in your program Referencing a null pointer Array index out of bounds May also be thrown and/or propagated by your program for run-time issues 11/2010 21

Constructors and Exceptions Up until now we ve had no way to recover if a bad parameter was passed to a constructor. We usually just exited the program with System.exit(). A better way is to throw an exception public BankAccount(double balance) throws InvalidAmountException{ if(balance < 0) throw new InvalidAmountException(balance); this.balance = balance; This code will not compile until you satisfy the Catch or Declare Rule. We can throw exceptions in constructors when class invariants are not maintained during construction. 11/2010 22

trying constructors public static void main(string[] args){ BankAccount account; try{ Scanner input = new Scanner(System.in); // get amount to deposit System.out.println("Enter a Starting Balance: "); double amt = input.nextdouble(); account = new BankAccount(amt); catch(invalidamountexception e){ System.err.println(e.getMessage()); catch(exception e){ System.err.println(e.getMessage()); Here we try to construct a BankAccount Object. Anytime we create an account with a amt < 0 and InvalidAmountException is thrown and delt with appropriately. 11/2010 23

The finally Block The finally block contains code to be executed whether or not an exception is thrown in a try block If it is used, a finally block is placed after a try block and its following catch blocks try {... catch( ExceptionClass1 e ) {...... catch( ExceptionClassN e ) {... finally { CodeToBeExecutedInAllCases 24

The finally Block If the try-catch-finally blocks are inside a method definition, there are three possibilities when the code is run: 1. The try block runs to the end, no exception is thrown, and the finally block is executed 2. An exception is thrown in the try block, caught in one of the catch blocks, and the finally block is executed 3. An exception is thrown in the try block, there is no matching catch block in the method, the finally block is executed, and then the method invocation ends and the exception object is thrown to the enclosing method 25

When to use a finally block The finally block should contain code that you always want to run whether or not an exception occurred. Generally the finally block contains code to release resources other than memory Close files Close internet connection Clear the screen 11/2010 26