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



Similar documents
Lecture J - Exceptions

15-214: Principles of Software Construction 8 th March 2012

Java Programming Language

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

Exceptions and their interpretation

D06 PROGRAMMING with JAVA

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

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

Java from a C perspective. Plan

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

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

Software Construction

Fundamentals of Java Programming

CS506 Web Design and Development Solved Online Quiz No. 01

Application Programming Interface

Exception Handling In Web Development DevelopIntelligence LLC

Using Files as Input/Output in Java 5.0 Applications

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Java Card Application Programming Interface

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

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

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

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

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

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

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

Crash Course in Java

Using Two-Dimensional Arrays

Agenda. What is and Why Polymorphism? Examples of Polymorphism in Java programs 3 forms of Polymorphism

J a v a Quiz (Unit 3, Test 0 Practice)

Enumerated Types in Java

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

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

Teach Yourself Java in 21 Minutes

Java Interview Questions and Answers

AP Computer Science Java Subset

AP Computer Science File Input with Scanner

The Interface Concept

Event-Driven Programming

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

An Exception Monitoring System for Java

Konzepte objektorientierter Programmierung

Chapter 1 Java Program Design and Development

Course Intro Instructor Intro Java Intro, Continued

Java Programming Fundamentals

Java Application Developer Certificate Program Competencies

Chapter 2 Introduction to Java programming

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

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

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

RMI Client Application Programming Interface

Lab Experience 17. Programming Language Translation

Programmation 2. Introduction à la programmation Java

Quick Introduction to Java

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

Form Validation. Server-side Web Development and Programming. What to Validate. Error Prevention. Lecture 7: Input Validation and Error Handling

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

Remote Method Invocation

Introducing Variance into the Java Programming Language DRAFT

WRITING DATA TO A BINARY FILE

Java Interfaces. Recall: A List Interface. Another Java Interface Example. Interface Notes. Why an interface construct? Interfaces & Java Types

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

CS170 Lab 11 Abstract Data Types & Objects

The first time through running an Ad Hoc query or Stored Procedure, SQL Server will go through each of the following steps.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Habanero Extreme Scale Software Research Project

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

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

C# and Other Languages

JCrasher: an automatic robustness tester for Java

Creating a Simple, Multithreaded Chat System with Java

Basic Java Constructs and Data Types Nuts and Bolts. Looking into Specific Differences and Enhancements in Java compared to C

Homework/Program #5 Solutions

Introduction to Java. CS 3: Computer Programming in Java

Chapter 5 Names, Bindings, Type Checking, and Scopes

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

Rigorous Software Development CSCI-GA

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

C++FA 3.1 OPTIMIZING C++

Pemrograman Dasar. Basic Elements Of Java

Chapter 8 Selection 8-1

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

language 1 (source) compiler language 2 (target) Figure 1: Compiling a program

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

Licence Informatique Année Exceptions

JAVA INTERVIEW QUESTIONS

Approach of Unit testing with the help of JUnit

JUnit - A Whole Lot of Testing Going On

Langages Orientés Objet Java

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

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

Compiling Object Oriented Languages. What is an Object-Oriented Programming Language? Implementation: Dynamic Binding

Network Communication

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

Transcription:

13. Exceptions To Err is Computer, To Forgive is Fine Dr. Who Exceptions are errors that are generated while a computer program is running. Such errors are called run-time errors. These types of errors are different from the errors that the compiler generates (called compile-time errors). Compile-time errors are generated in response to erroneous syntax in the source code. Run-time errors are generated in response to erroneous semantics. For example, it is not a compile-time error to divide by zero, but it is a run-time error. 13.1 Generating your first exception Suppose you want to divide two numbers. If you cause the computer to divide by zero, an exception will be thrown at run-time: public class ExceptionExample { System.out.println( "f(0)=" + f(0)); public static int f(int x) { return 1/x; This generates the following run-time error: Exception in thread "main" java.lang.arithmeticexception: / by zero at ExceptionExample.f(ExceptionExample.java) at ExceptionExample.main(ExceptionExample.java)

188 Java for Programmers 13.2 Intercepting the Run-time Error We intercept the error before it occurs. This is called guarding the input. For example, we could say: public static int f(int x) { if (x == 0) return 0; return 1/x; But this would return an invalid answer for a bad input (which is actually much worse than stopping the program and informing the user). To intercept an exception, after it has been thrown, you use a try-catch block: public class ExceptionExample { System.out.println( "f(0)=" + f(0)); catch (ArithmeticException e) { System.out.println("Bad input for f!"); System.out.println("program continues..."); public static int f(int x) { return 1/x; This outputs: Bad input for f! program continues... We see that the program does not stop suddenly, when dividing by zero. When a run-time error occurs, according to the Java Language Specification [Gosling], the Java machine will throw an exception. When an exception is thrown, a non-local transfer of control occurs from the area that generated the exception to a place that can catch the exception. In our case, we caught the exception, emitted an error

Java for Programmers 189 message, and then allowed the program to continue. The interesting part about this approach is that we can select where the error handling occurs, and protect the program from bombing during a mission-critical area of the code. 13.3 Defining your own Exception Suppose you are interested in building a credit card processing routine. You want the routine to perform an elementary check on the credit card number, and if there is a problem, it throws an exception. When our check finds a problem, a new exception is thrown called a CreditCardException. Here is how we define it: public class CreditCardException extends Exception { public CreditCardException(String s) { super(s); public static void check(int i) throws CreditCardException { if (i < 0) { throw new CreditCardException( "credit card ="+i); The Exception class is defined in the java.lang package. A new exception may be defined by sub-classing the Exception class. The class that does the credit card check only checks to make sure that the credit card is positive. However, this is an implementation detail, and a more complete credit card check could easily be performed. Here is a class that checks the credit card: public class CheckCreditCard { CreditCardException.check(-9); catch (CreditCardException e) { e.printstacktrace(); System.out.println("Heres the cc exception"); return; System.out.println("done.");

190 Java for Programmers 13.4 Checked and Unchecked Exceptions There are two kinds of exceptions, checked and unchecked. When a method is invoked that throws a checked exception, then the invoking method must place the invocation in a try-catch block, or declare it in the throws clause. For example: public static void check(int i) { CreditCardException.check(-9); Causes a compile-time error: Error : Exception CreditCardException must be caught, or it must be declared in the throws clause of this method. ExceptionExample.java line 41 CreditCardException.check(- 9); Thus, we have two possible actions, declare the CreditCardException in the throws clause: public static void check(int i) throws CreditCardException { CreditCardException.check(-9); Or we can place the invocation inside a try-catch block: public static void check(int i) { CreditCardException.check(-9); catch(creditcardexception e) { e.printstacktrace(); The checked is defined by sub-classing the Exception class. The unchecked exception is defined by sub-classing the RuntimeException class. With an unchecked exception, No try-catch construct is needed to invoke methods or

Java for Programmers 191 statements that throw RuntimeExceptions. For example, dividing by zero can throw a RuntimeException. Figure 13.4-1 shows the java.lang Exception subclass hierarchy. java.lang.classnotfoundexception java.lang.clonenotsupportedexception java.lang.illegalaccessexception java.lang.throwable java.lang.exception java.lang.instantiationexception java.lang.interruptedexception java.lang.nosuchmethodexception java.lang.runtimeexception Figure 13.4-1. An overview of the java.lang exception classes A zoom in of the java.lang.runtimeexception class hierarchy is shown in Figure 13.4-2. java.lang.arithmeticexception java.lang.arraystoreexception java.lang.classcastexception java.lang.illegalargumentexception java.lang.exception java.lang.runtimeexception java.lang.illegalmonitorstateexception java.lang.indexoutofboundsexception java.lang.negativearraysizeexception java.lang.nullpointerexception java.lang.securityexception Figure 13.4-2. An overview of the java.lang.runtimeexception classes

192 Java for Programmers 13.5 The MBNF for the try statement The Modified Backus Naur Form (MBNF) for the try-catch block is: trystatement "try" statement < "catch" "(" parameter ")" statement > [ "finally" statement]. It is typical to use the try-catch block with any code that might fail. As seen with the division example, given above, there was no requirement for the try-catch block. Thus, there was no requirement that the code be able to handle run-time errors locally. A typical pattern for the try-catch block follows:... catch (... ) {... catch (... ) {...... For example: // create an instance of your applet class a = (Applet) Class.forName(className).newInstance(); catch (ClassNotFoundException e) { System.out.println( "ClassNotFoundException in AppletFrame"); return; catch (InstantiationException e) { System.out.println( "InstantiationException in AppletFrame"); return; catch (IllegalAccessException e) { System.out.println( "IllegalAccessException in AppletFrame"); return;

Java for Programmers 193 When an exception is caught, a message is obtainable as an instance of a string, using: e.getmessage() A sophisticated program might log the messages from the exceptions (called error logging) so that proper steps can be taken to correct the error. At the other extreme, we could catch the exceptions and then continue running, ignoring all exceptions. For example: out.write(buffer); catch(exception e) { A new exception is defined by extending the Exception class. For example: class FileFormatException extends Exception { public FileFormatException(String s) { super(s); Try catch blocks can slow down the execution of code slightly. They create a local scope of variables. It is therefore important to place exceptions at the right level of granularity. It would not be appropriate to, for example, place every division inside of a try-catch block. It would be better practice to program by assertion. Programming by assertion protects the input to a method so that it is reasonable and unlikely to cause an exception. The checked exception decends from the Exception class. Such exceptions do require a try-catch statement, or are required to be in methods that throw a checked exception. For example: public class ThrowsExample { Float value = Float.valueOf("1.0"); System.out.println(value); value = Float.valueOf("blah blah blah"); System.out.println(value);

194 Java for Programmers Will output: 1.0 _exceptionoccurred: java.lang.numberformatexception (blah blah blah) java.lang.numberformatexception: blah blah blah at java.lang.float.valueof(float.java) at ThrowsExample.main(TrivialApplication.java) at com.apple.mrj.jmanager.jmstaticmethoddispatcher.run(jma WTContextImpl.java) at java.lang.thread.run(thread.java) The java.lang.numberformatexception is an unchecked or RuntimeException, sine the NumberFormatException subclasses the IllegalArgumentException, which subclasses the RuntimeException. With checked exceptions, the try-catch block is required. For example: public class FileExample { public static File openfile() { return new File("foo.txt"); public static FileReader openfilereader() { return new FileReader(openFile()); System.out.println(openFileReader()); Will not compile. The syntax error is: Error : Exception java.io.filenotfoundexception must be caught, or it must be declared in the throws clause of this method. TrivialApplication.java line 23 return new FileReader(openFile()); The following shows a way to fix the code: public class FileExample { public static File openfile() { return new File("foo.txt"); public static FileReader openfilereader() throws FileNotFoundException {

Java for Programmers 195 return new FileReader(openFile()); System.out.println(openFileReader()); catch(filenotfoundexception e) { e.printstacktrace(); In summary, 1. An exception is a run-time condition. 2. Exceptions can be thrown by any instance of a class that subclasses java.lang.throwable. 3. Exceptions must be caught in order to be intercepted and processed. 4. A try-catch block can be used to process exceptions 5. The finally clause is always executed. 6. Checked exceptions subclass the Exception class. 7. Unchecked exceptions subclass the RuntimeException class. 13.6 Exercises 1. A Master card number is a positive integer that has 16 digits. Design a credit card checking routine that throws a CreditCardException when the number of digits in the credit card is invalid. 2. Write a program that computes how much it costs to leave a computer on 24 hours a day, 7 days a week. Assume that the computer uses 0.2 KW/Hr and that power costs 10 cents per KW-Hr. Tabulate the costs of operating a computer as a function of the cost of power. In crease the cost of power by 5 cents per Kw-Hr until you get to 50 cents per Kw-Hr. Use a function to perform the computation. Make the cost of power and total amount of power consumed parameters. If the

196 Java for Programmers parameters are negative, throw an InvalidPowerException. Make this a RuntimeException so that try-catch blocks are not required.