Contents. 4-1 Copyright (c) 1999 N. Afshartous

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

Lecture J - Exceptions

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

Using Files as Input/Output in Java 5.0 Applications

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

D06 PROGRAMMING with JAVA

CS506 Web Design and Development Solved Online Quiz No. 01

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

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

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

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

JAVA - FILES AND I/O

What are exceptions? Bad things happen occasionally

Fundamentals of Java Programming

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

Java from a C perspective. Plan

AP Computer Science Java Subset

WRITING DATA TO A BINARY FILE

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

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

Creating a Simple, Multithreaded Chat System with Java

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

D06 PROGRAMMING with JAVA

Teach Yourself Java in 21 Minutes

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

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

Crash Course in Java

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

1. Properties of Transactions

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

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

Chapter 5 Names, Bindings, Type Checking, and Scopes

Building a Multi-Threaded Web Server

Java Interview Questions and Answers

INPUT AND OUTPUT STREAMS

Stack Allocation. Run-Time Data Structures. Static Structures

AVRO - SERIALIZATION

Programmation 2. Introduction à la programmation Java

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

CS 1302 Ch 19, Binary I/O

An Overview of Java. overview-1

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

CS170 Lab 11 Abstract Data Types & Objects

CS193j, Stanford Handout #10 OOP 3

Contents. 9-1 Copyright (c) N. Afshartous

Java Application Developer Certificate Program Competencies

Cohort: BCA/07B/PT - BCA/06/PT - BCNS/06/FT - BCNS/05/FT - BIS/06/FT - BIS/05/FT - BSE/05/FT - BSE/04/PT-BSE/06/FT

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

Software Construction

COMP 356 Programming Language Structures Notes for Chapter 10 of Concepts of Programming Languages Implementing Subprograms.

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

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

No no-argument constructor. No default constructor found

Continuous Integration Part 2

JAVA INTERVIEW QUESTIONS

Software Engineering Techniques

Exception Handling In Web Development DevelopIntelligence LLC

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

Java Coding Practices for Improved Application Performance

Lab Experience 17. Programming Language Translation

Simple Java I/O. Streams

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

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

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

C++ INTERVIEW QUESTIONS

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

java Features Version April 19, 2013 by Thorsten Kracht

Course Intro Instructor Intro Java Intro, Continued

Java CPD (I) Frans Coenen Department of Computer Science

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

AP Computer Science File Input with Scanner

Computing Concepts with Java Essentials

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

Zebra and MapReduce. Table of contents. 1 Overview Hadoop MapReduce APIs Zebra MapReduce APIs Zebra MapReduce Examples...

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

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

Dennis Olsson. Tuesday 31 July

Classes Dennis Olsson

How To Write A Program In Java (Programming) On A Microsoft Macbook Or Ipad (For Pc) Or Ipa (For Mac) (For Microsoft) (Programmer) (Or Mac) Or Macbook (For

Files and input/output streams

Java Programming Language

Object-Oriented Programming in Java

What is an I/O Stream?

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

Chapter 1 Java Program Design and Development

CSE 1020 Introduction to Computer Science I A sample nal exam

RMI Client Application Programming Interface

Compile-time type versus run-time type. Consider the parameter to this function:

Enumerated Types in Java

Input / Output Framework java.io Framework

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

JAVA.UTIL.SCANNER CLASS

Statements and Control Flow

On the (un)suitability of Java to be the first programming language

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

Event-Driven Programming

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

Time Limit: X Flags: -std=gnu99 -w -O2 -fomitframe-pointer. Time Limit: X. Flags: -std=c++0x -w -O2 -fomit-frame-pointer - lm

Transcription:

Contents 1. Classes and Objects 2. Inheritance 3. Interfaces 4. Exceptions and Error Handling 5. Intro to Concurrency 6. Concurrency in Java 7. Graphics and Animation 8. Applets 4-1 Copyright (c) 1999 N. Afshartous

Chapter 4: Exceptions and Error Handling After this chapter you will be able to: - Use throw to generate Exceptions - Handle Exceptions with catch - Add throws to method declarations - Customize exception handling 4-2 Copyright (c) 1999 N. Afshartous

Motivation Exception are a mechanism for handling runtime errors Advantages: flexible model clean separation of error handling code from application code Disadvantages: extra run-time overhead 4-3 Copyright (c) 1999 N. Afshartous

History Exception handling was introduced in Ada83 and is now present in: C++ Common Lisp Java Standard ML SmallTalk Conclusion: Exception handling is the de facto standard mechanism for error handling in modern programming languages 4-4 Copyright (c) 1999 N. Afshartous

Metaphors The two basic ideas are: throw: at some point when an error occurs during execution an exception object is created and thrown catch: an exception object may be caught and handled at some other point in the program 4-5 Copyright (c) 1999 N. Afshartous

Java Exception Classes Exception RunTimeException AWTException IOException ArithmeticException EOFException ClassNotFoundException IndexOutOfBounds Exception FileNotFoundException NullPointerException 4-6 Copyright (c) 1999 N. Afshartous

Overview Of Exception Handling When an exception is thrown normal execution stops! A search is then performed for a corresponding catch to handle the error If no corresponding catch is found then the program terminates 4-7 Copyright (c) 1999 N. Afshartous

Generating Exceptions Explicitly Can call an Exception constructor new Exception( error description ); and then throw an exception object explicitly throw new Exception( error description ); If the Exception is not caught and handled then execution terminates 4-8 Copyright (c) 1999 N. Afshartous

Generating Exceptions Implictly No throw appears here int a = b / c; However dividing by zero will generate an ArithmeticException 4-9 Copyright (c) 1999 N. Afshartous

Catching Exceptions try { application code catch error handling code If the application code generates an exception and there is a corresponding catch then the error handling code is executed try { int y = 4 / x; catch (ArithmeticException e) { System.out.println( divide by zero occurred ; Variable e is bound to the caught Exception object 4-10 Copyright (c) 1999 N. Afshartous

Stack Trace Can use the Exception object to print a stack trace try { int y = 4 / x; catch (ArithmeticException e) { System.out.println( divide by zero occurred ; e.printstacktrace(); A stack trace is the sequence of methods called up to the point where the Exception was thrown 4-11 Copyright (c) 1999 N. Afshartous

Multiple Catches Can have multiple catch branches to handle different kinds of Exceptions try { foo(); catch (ArithmeticException e) { System.out.println( divide by zero occurred ; catch (Exception e) { System.out.println( Some kind of Exception occurred ; The first catch that matches the thrown object is executed 4-12 Copyright (c) 1999 N. Afshartous

Compiler Error More specific catch branches must precede the more general try { foo(); catch (Exception e) { System.out.println( Some kind of Exception occurred ; catch (ArithmeticException e) { System.out.println( divide by zero occurred ; What is wrong? 4-13 Copyright (c) 1999 N. Afshartous

Compiler Checking The Java compiler enforces that Exceptions will be handled * * Except for subclasses of RunTimeException IndexOutOfBoundsException NullPointerException ArithmeticException... The compiler performs no checking for subclasses of RuntimeException (generally, these should not be caught) 4-14 Copyright (c) 1999 N. Afshartous

Compiler Error FileInputStream constructor may throw a FileNotFoundException import java.io.fileinputstream; FileInputStream inputfile = new FileInputStream( f1.dat ); Compiler error: FileNotFoundException not caught or declared 4-15 Copyright (c) 1999 N. Afshartous

Catching IOException Catching the IOException is one way to satisfy the compiler import java.io.fileinputstream; try { FileInputStream inputfile = new FileInputStream( f1.dat ); catch (java.io.filenotfoundexception e) { System.out.println( File not found ); Declaring that an exception may be thrown is another way 4-16 Copyright (c) 1999 N. Afshartous

RunTimeException Subclasses Indexing into an array may cause an IndexOutOfBoundsException int [] x = {1,2,3,4 for (int i = 0; i < x.length; i++) sum += x[i]; IndexOutOfBoundsException is a subclass of RunTimeException (no compiler checking) 4-17 Copyright (c) 1999 N. Afshartous

Declaring Exceptions A method may declare that an exception may be thrown using keyword throws public char Read () throws java.io.ioexception { System.out.println("Enter input char: "); return (char) System.in.read(); No try-catch necessary here 4-18 Copyright (c) 1999 N. Afshartous

Exceptions Propogate If a thrown Exception is not caught inside a method then the Exception will propogate to the point where the method was called (and so on until caught) public void method1 () { try { method2(); // Exception propogates to here catch (Exception e) { System.out.println("caught it here"); public void method2 () throws Exception { throw new Exception(); 4-19 Copyright (c) 1999 N. Afshartous

Rethrowing An Exception may be caught and then thrown again import java.io.fileinputstream; try { FileInputStream inputfile = new FileInputStream(fileName); catch (java.io.filenotfoundexception e) { if (filename.equal( default.dat )) e.fillinstackstrace(); throw e; fillinstacktrace resets the stack trace 4-20 Copyright (c) 1999 N. Afshartous

Flexibility The propogation of Exceptions provides flexibility An exception object may be caught locally or at another point further up the call trace An Exception should be caught locally if it can be handled properly 4-21 Copyright (c) 1999 N. Afshartous

Customizing Exceptions Create a subclass of class Exception import java.util.date; class DatedException extends Exception { Date d; public DatedException () { d = new Date(); // store's current time public String tostring () { // return string representation return d.tostring(); 4-22 Copyright (c) 1999 N. Afshartous

Catching DatedException Can print out the time of the error public static void main (String [] args) { try { foo(); catch (DatedException e) { System.out.println( Error occurred on: " + e); Output Error occurred on: Thu Oct 08 10:48:54 1998 4-23 Copyright (c) 1999 N. Afshartous

Over Using Exceptions Question: What is wrong here? char c; try { FileInputStream f = new FileInputStream("f1"); while (true) { c = (char) f.read(); System.out.print(c); catch (java.io.eofexception e) { System.out.println("end of file reached "); catch (java.io.ioexception e) { System.out.println("I/O error occurred"); 4-24 Copyright (c) 1999 N. Afshartous

Answer Exceptions are meant for exceptional (not expected) conditions When reading from a data file, it is expected that the end of file will be reached Similarly when indexing into arrays and strings, it is expected that the end will be reached Conclusion: Don t use exceptions for expected conditions due to overhead and extra code required 4-25 Copyright (c) 1999 N. Afshartous

File Input Revised Can test to see if read returned a valid byte char c; try { FileInputStream f = new FileInputStream("f1"); while ((c = (char) f.read()) > -1) { c = (char) f.read(); System.out.print(c); catch (java.io.ioexception e) { System.out.println( "I/O error occurred during read"); 4-26 Copyright (c) 1999 N. Afshartous

Finally finally is used to guarantee that code is executed whether or not an Exception occurs try { while (true) { x.dotransaction(); catch (DatedException e) { System.out.println( Error occurred on: " + e); finally { logfile.write( attempted: + x.getid()); Can have one finally in a try-catch 4-27 Copyright (c) 1999 N. Afshartous

It s Exercise Time 4-28 Copyright (c) 1999 N. Afshartous