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



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

Software Engineering Techniques

Lecture J - Exceptions

Java Programming Language

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

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

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

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

Chapter 1 Fundamentals of Java Programming

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

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

Software Construction

D06 PROGRAMMING with JAVA

Fundamentals of Java Programming

AP Computer Science Java Subset

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

Java Interview Questions and Answers

The Interface Concept

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

No no-argument constructor. No default constructor found

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

CS506 Web Design and Development Solved Online Quiz No. 01

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

Polymorphism. Why use polymorphism Upcast revisited (and downcast) Static and dynamic type Dynamic binding. Polymorphism.

History OOP languages Year Language 1967 Simula Smalltalk

CS193j, Stanford Handout #10 OOP 3

Introduction to Java

Java Application Developer Certificate Program Competencies

Object-Oriented Programming in Java

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

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

C++ INTERVIEW QUESTIONS

Java CPD (I) Frans Coenen Department of Computer Science

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

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

Java Memory Model: Content

Crash Course in Java

WRITING DATA TO A BINARY FILE

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

Moving from CS 61A Scheme to CS 61B Java

Inheritance, overloading and overriding

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

Teach Yourself Java in 21 Minutes

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

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

Class 16: Function Parameters and Polymorphism

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

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

Exception Handling In Web Development DevelopIntelligence LLC

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

Course Intro Instructor Intro Java Intro, Continued

Stack Allocation. Run-Time Data Structures. Static Structures

Chapter 13 - Inheritance

JAVA - INHERITANCE. extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword.

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

Java Programming Fundamentals

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson

How to create/avoid memory leak in Java and.net? Venkat Subramaniam

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

Programmation 2. Introduction à la programmation Java

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

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

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

Object-Oriented Programming Lecture 2: Classes and Objects

Java from a C perspective. Plan

Java (12 Weeks) Introduction to Java Programming Language

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

Chapter 2 Introduction to Java programming

Remote Method Invocation

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

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

JAVA INTERVIEW QUESTIONS

An Overview of Java. overview-1

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

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

16.1 DataFlavor DataFlavor Methods. Variables

INTRODUCTION TO OBJECTIVE-C CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 12 09/29/2011

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

OBJECT ORIENTED PROGRAMMING LANGUAGE

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

Rigorous Software Development CSCI-GA

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

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

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

Reading Input From A File

1001ICT Introduction To Programming Lecture Notes

Java Programming. Binnur Kurt Istanbul Technical University Computer Engineering Department. Java Programming. Version 0.0.

Computing Concepts with Java Essentials

CMSC 202H. ArrayList, Multidimensional Arrays

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Description of Class Mutation Mutation Operators for Java

Tutorial: Getting Started

C# and Other Languages

Getting Started with the Internet Communications Engine

Habanero Extreme Scale Software Research Project

Transcription:

Exception Handling Error handling in general Java's exception handling mechanism The catch-or-specify priciple Checked and unchecked exceptions Exceptions impact/usage Overloaded methods Interfaces Inheritance hierarchies Constructors OOP: Exception Handling 1

Error Handling Not all errors can be caught at compile time! Help -- run-time error! What next? First ideas: System.out.println() System.err.println() (much better than the previous) Good guess but some errors call for corrective action, not just warning. In general, printing is a bad idea! Better: tell someone (not necessarily the user)! OOP: Exception Handling 2

Error Handling, cont. Establish return code convention 0 vs.!0 in C/C++ boolean in Java Set value of a global variable Done in many shells. In Java use a public static field in a class. Raise an exception, catch it, and act The idea comes from hardware. Modern language support (Java, Python, Lisp, Ada, C++, C#). OOP: Exception Handling 3

General Errors and Error Handling Error must be handled where the occur One error in a method can be handled very differently in the clients, this is not a good approach. Repeating handling of the same error. Can be extremely hard to debug. To handle an error detailed information on the error must be provided. Where did the error occur (class, method, line number) What type of error A good error message Dump of runtime stack? (too much information?) In object-oriented languages errors are represented by objects. OOP: Exception Handling 4

How to Handle Errors Ignore: False alarm just continue. Report: Write a message to the screen or to a log. Terminate: Stop the program execution. Repair: Make changes and try to recover the error. To be able to repair would be the best. However, often the best that can be done is the combination of report and terminate. OOP: Exception Handling 5

Java's Exception Handling Exception: An event that occurs during the execution of a program the disrupts the normal transaction flow. A run-time phenomenon. Exception handling is part of the language. Exceptions are objects. Exceptions are structured in a class hierarchy. It is not possible to ignore an exceptions (nice feature?). A method specifies, which exception may occur, the client must anticipate these exceptions, otherwise compile-time error. It is sometimes possible to recover to a known good state after an exception was raised. OOP: Exception Handling 6

Java's Exception Handling, cont. Java s object-oriented way to handle errors more powerful, more flexible than using return keywords try, catch, throw, throws, finally. An exception is an object that describes an erroneous or unusual situation. Exceptions are thrown by a program, and may be caught and handled by another part of the program. A program can therefore be separated into a normal execution flow and an exception execution flow. An error is also represented as an object in Java, but usually represents a unrecoverable situation and should not be caught. OOP: Exception Handling 7

Motivation for Exception Handling errorcodetype readfile { initialize errorcode = 0; open the file; if (thefileisopen) { determine the length of the file; if (gotthefilelength) { allocate that much memory; if (gotenoughmemory) { read the file into memory; if (readfailed) { errorcode = -1; else { errorcode = -2; else { errorcode = -3; close the file; if (thefiledidntclose && errorcode == 0) { errorcode = -4; else { errorcode = errorcode and -4; else { errorcode = -5; return errorcode; readfile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; catch (fileopenfailed) { dosomething; catch (sizedeterminationfailed) { dosomething; catch (memoryallocationfailed) { dosomething; catch (readfailed) { dosomething; catch (fileclosefailed) { dosomething; [source: java.sun.com] OOP: Exception Handling 8

Exception Handling Model Code where you anticipate a problem: Detect error, probably with an if create a new exception and throw it Alternatively let JVM detect error, create, and throw an exception Code in client (somewhere in message invocation stack) public static void main (String args[]) throws exception1, exception2, exception3 {... try, hoping for the best prepare to catch an exception try{ // statements that can throws exceptions... catch (exception1) { // do stuff catch (exception2) { // do stuff OOP: Exception Handling 9

Simple Example public class SimpleException extends Exception{ public class SimpleExample{ public double calcprice(int netprice) throws SimpleException{ if (netprice > 100){ throw new SimpleException(); // to expensive return netprice * 1.25; // add sales tax public static void main (String[] args){ SimpleExample se = new SimpleExample(); try{ se.calcprice(10); se.calcprice(23); se.calcprice(1000); se.calcprice(88); // never called catch(simpleexception e){ System.err.println("Caught SimpleException"); OOP: Exception Handling 10

Catch Specify Java's Catch or Specify Requirement A method can catch exception by providing and exception handler. If a method chooses not to catch, then specify which exceptions are thrown. Exceptions are part of a method's public interface. OOP: Exception Handling 11

Checked/Unchecked Exceptions An exception is either checked or unchecked Checked = checked by the compiler A checked exception can only be thrown within a try block or within a method that is designated to throw that exception. The compiler will complain if a checked exception is not handled appropriately. An unchecked exception does not require explicit handling, though it could be processed that way. An an example many run-time exceptions are unchecked exceptions. OOP: Exception Handling 12

Java's Exception Class Hierarchy Checked Object Throwable Checked Error Exception Subclasses Subclasses RunTimeException Unchecked (System and JVM Errors) Checked Unchecked Subclasses OOP: Exception Handling 13

Java's Exception Class Hierarchy, cont. Throwable Error Superclass for all exceptions Two methods for filling in and printing the stack Serious internal errors (should not occur in running programs). Are normally not handled. (report and terminate) Programs should not throw Error The catch or specify principle does not apply, because they are so severe. Examples Dynamic linking failure Memory shortage Instantiating abstract class OOP: Exception Handling 14

Java's Exception Class Hierarchy, cont. Exception The base class for most exception used in Java programs The catch or specify principle does apply Examples of subclasses IOException ClassNotFoundException RuntimeException Not a good name (all exceptions are at run-time)! Commonly seen run-time error The catch or specify principle does not apply, because they are so ubiquitous. Examples Divide by zero/cast error/null pointer OOP: Exception Handling 15

The try Statement To process an exception when it occurs, the line that throws the exception is executed within a try block. A try block is followed by one or more catch clauses, which contain code to process an exception. Each catch clause has an associated exception type. try { // statements OOP: Exception Handling 16

The catch Statement The catch statement is used for catching exceptions. A try statement must be accompanied by a catch statement. Try and catch statements can be nested, i.e., try block in try block, etc. try {... catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught first " + e.getmessage()); catch (IOException e) { System.err.println("Caught second " + e.getmessage()); OOP: Exception Handling 17

The catch Statement, cont. When an exception occurs, processing continues at the first catch clause that matches the exception type. The catch statements should be should be listed in most-specialized-exception-first order. try {... catch (Exception e) { // very general exception System.err.println("Caught first " + e.getmessage()); catch (ArrayIndexOutOfBoundsException e) { // will never be called System.err.println("Caught second " + e.getmessage()); OOP: Exception Handling 18

The finally Clause A try statement can have an optional clause designated by the reserved word finally. If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete. Also, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete. try { // statements that throw exceptions catch(<exception>) { // do stuff finally { // code here runs whether or not catch runs OOP: Exception Handling 19

The finally Clause, cont. previous statement try FirstException SecondException finally next statement OOP: Exception Handling 20

The finally Clause, Example try { out = new PrintWriter(new FileWriter("out.txt")); // statements that throws exceptions catch (ArrayIndexOutOfBoundsException e) { System.err.println("Caught array error"); catch (IOException e) { System.err.println("Caught I/O error"); finally { if (out!= null) { System.out.println("Closing file"); out.close(); OOP: Exception Handling 21

The throw Statement All methods use the throw statement to throw an exception. public Object pop() throws EmptyStackException { Object obj; if (size == 0) throw new EmptyStackException(); obj = objectat(size 1); setobjectat(size - 1, null); size--; return obj; [source: java.sun.com] OOP: Exception Handling 22

Exception Propagation If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level. Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level. A try block that contains a call to a method in which an exception is thrown can be used to catch that exception. OOP: Exception Handling 23

Exception Propagation, Example static void method1 throws IOException { throw new IOException("Error in method1"); static void method2 throws IOException { // do stuff, but no catch, just specify method1(); static void method3 throws IOException { // do stuff, but no catch, just specify method2(); public static void main (String args[]){ // catch if just specify error to console try { method3(); catch (IOException e){ // handle the exception from method1 OOP: Exception Handling 24

Rethrowing an Exception static void method1 throws IOException { throw new IOException("Error in method1"); static void method2 throws IOException { try{ method1(); catch (IOException e) { System.err.printly ("Handle partly here"); throw e; // 1st method // throw e.fillinstacktrace; // 2nd method // throw new IOException ("new one"); // 3th method public static void main (String args[]){ // catch if just specify error to console try { method2(); catch (IOException e){ System.err.printly ("Handle rest here"); OOP: Exception Handling 25

Creating New Exceptions Requires careful design (part of the public interface). Can an existing Exception be used? Choose the correct superclass. Choosing the name The most important thing for new exceptions. Tends to be long an descriptive (ArrayIndexOutOfBoundsException) Code for exception class typically minimal Naming convention: All classes that inherits from Exception has 'Exception' postfixed to their name. All classes that inherits from Error has 'Error' postfixed to their name. OOP: Exception Handling 26

Creating New Exceptions, Example class SimplestException extends Exception { // empty method body okay, just give it a good name class SimpleException extends Exception { SimpleException () { super(); // default constructor SimpleException (String str) { super(str); class ExtendedException extends Exception { private static int counter = 0; // no of exceptions ExtendedException () { super(); counter++; ExtendedException (String str) { super(str); counter++; ExtendedException (String str, int no) { super(str); instanceno = no; counter++; OOP: Exception Handling 27

Overloading and Exception Methods cannot be overloaded based on exception specification. public class OverloadedMethod{ /** An overloaded method */ public int calc(int x) throws SimpleException { return x; /** NOT allowed */ public int calc(int y) throws AnotherException { return y; /** Is allowed */ public int calc(int x, int y){ return x + y; public static void main(string[] args){ OverloadedMethod om = new OverloadedMethod(); System.out.println(om.calc(3)); OOP: Exception Handling 28

Interfaces and Exception Exceptions can naturally be specified for methods in interfaces public interface InterfaceException{ int calc(int x) throws SimpleException; // not allowed //int calc(int y) throws AnotherException; int calc(int x, int y) throws SimpleException, AnotherException; OOP: Exception Handling 29

Inheritance and Exceptions If base-class method throws an exception, derived-class method may throw that exception or one derived from it. Derived-class method cannot throw an exception that is not a type/subtype of an exception thrown by the base-class method. Otherwise subclass cannot be upcasted to base-class. class BaseException extends Exception{ class DerivedException extends BaseException{ class A { void f() throws BaseException{ class B extends A { void f() throws DerivedException{ // not allowed compile-error class C extends B { void f() throws AnotherException{ OOP: Exception Handling 30

Inheritance and Constructors Constructors can throw exceptions Subclass constructor cannot catch exception throws by base class constructor. class A{ int i; A(int j) throws SimpleException{ if (j < 0){ throw new SimpleException(); i = j; class B extends A { B(int j) throws SimpleException, AnotherException{ // cannot have try block here super(j); if (j > 100){ throw new AnotherException(); OOP: Exception Handling 31

Guidelines Do not use exceptions for normal control flow! Slows down the program Do use exceptions to indicate abnormal conditions! Handle the error (fully or partially) if you have enough information in the current context. Otherwise, propagate! Handle group of statements Do not encompass every single statement in a try block Use exceptions in constructors! Do something with the exceptions your code catches! Clean up using finally. OOP: Exception Handling 32

Summary The manner in which an exception is processed is an important design consideration. Advantages of Exceptions Separates error handling from regular code. Propagation of errors up the call stack. Handle error in a context Grouping of error type and differentiation of errors. Overview Reuse of error handling code OOP: Exception Handling 33