Docsity

Effective Java: Exceptions and Exception Handling in Java, Papers of Computer Science

Partial preview of the text

Download Effective Java: Exceptions and Exception Handling in Java and more Papers Computer Science in PDF only on Docsity!

CMSC 132:

Object-Oriented Programming II

Exceptions & Effective Java

Department of Computer Science

University of Maryland, College Park

Overview

Exceptions

Motivation Representation in Java

Effective Java

Problem

May not be able to handle error locally

Not enough information in method / class Need more information to decide action

Handle exception in calling function(s) instead

Decide at application level (instead of library) Examples

Incorrect data format

ask user to reenter data

Unable to open file

ask user for new filename

Insufficient disk space

ask user to delete files

Will need to

propagate

exception to caller(s)

Exception Handling – Exit Program Approach

Exit program with error message / error code

Example^ if (error) {

System.err.println(“

Error found

// message

System.exit(

// error code

} Problem

Drastic solution Event must be handled by user invoking program Program may be able to deal with some exceptions

Exception Handling – Throw Exception

Approach

Throw exception (caught in parent’s

catch

block)

Example^ A( ) {

if (error)

throw

new ExceptionType();

} B( ) {

try {

A( );

} catch

(ExceptionType e) { ...action... }

Java exception backtracks tocaller(s) until matching catchblock found

Exception Handling – Throw Exception

Advantages

Compiler ensures exceptions are caught eventually No need to explicitly

propagate

exception to caller

Backtrack

to caller(s) automatically

Class hierarchy defines meaning of exceptions

No need for separate definition of error codes Exception handling code separate & clearly marked

Representing Exceptions

Java Exception class hierarchy

Two types of exceptions

checked & unchecked

Object^ Object

Error^ Error

Throwable^ Throwable

Exception^ Exception

ClassNotFoundException^ ClassNotFoundExceptionCloneNotSupportedException^ CloneNotSupportedExceptionIOException^ IOExceptionAWTException^ AWTExceptionRuntimeException^ RuntimeException … LinkageError^ LinkageErrorVirtualMachoneError^ VirtualMachoneErrorAWTError^ AWTError …

ArithmeticException^ ArithmeticExceptionNullPointerException^ NullPointerExceptionIndexOutOfBoundsException^ IndexOutOfBoundsException

Checked^ CheckedUnchecked^ Unchecked NoSuchElementException^ NoSuchElementException …

Representing Exceptions

Java Exception class hierarchy

Checked Exceptions

Class

Exception

(except RunTimeException)

Errors typical program should handle Used for operations prone to error Example

IOException, ClassNotFoundException

Compiler requires “

catch or declare

Catch and handle exception in method, OR Declare method can throw exception, force callingfunction to catch or declare exception in turn Example^ void A( ) throws ExceptionType { … }

Designing & Using Exceptions

Use exceptions only for rare events

Not for common cases

checking end of loop

High overhead to perform catch

Place statements that jointly accomplish taskinto single try / catch block Use existing Java Exceptions if possible

Overview

Exceptions Effective Java

Puzzlers Principles

Effective Java

Title

Effective JavaProgrammingLanguage Guide

Author

Joshua Bloch

Contents

Useful tips forJava programming

What's In A Name?

public class Name {

private String myName;public Name(String n) { myName = n; }public boolean equals(Object o) {

if (!(o instanceof Name)) return false;Name n = (Name)o;return myName.equals(n.myName); } public static void main(String[ ] args) {

Set s = new HashSet();s.add(new Name("Donald"));System.out.println(s.contains(new Name("Donald"))); } }

Output 1.

True

False

It Varies Name classviolates JavahashCode( )contract.If you overrideequals( ), mustalso overridehashCode( )!

You're Such A Character

public class Trivial {

public static void main(String args[ ]) {

System.out.print("H" + "a");System.out.print('H' + 'a'); } }

Output 1.

Ha

HaHa

Neither

Prints Ha169'H' + 'a' evaluated as

int

then converted to String!Use string concatenation(+) with care. At least oneoperand must be a String