Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Exception Handling, Zero Java - Lecture Slides | CS 230, Exams of Data Structures and Algorithms

Material Type: Exam; Class: LAB: Data Structures; Subject: Computer Science; University: Wellesley College; Term: Spring 2009;

Typology: Exams

Pre 2010

Uploaded on 08/18/2009

koofers-user-vx6-1
koofers-user-vx6-1 🇺🇸

4

(1)

10 documents

1 / 4

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
3/10/09
1
10.1 – Exceptions vs Errors
! An exception is an object describing unusual or erroneous situation
Division by 0 in computing expression (ArithmeticException)
Array index out of bounds (IndexOutOfBoundsException)
Null pointer cannot be followed (NullPointerException)
I/O problems (e.g., no space on disk to save file, file not found)
No permissions to do something (e.g., save a file)
! Exceptions are thrown by a program,
and may be caught and handled by another part of the program
! A program can be separated into a normal execution flow and
an exception execution flow
! (An error is also an object,
but it represents a unrecoverable situation and should not be caught)
1-1
10.1 – Exception Handling
! Java has a predefined set of exceptions and errors
that can occur during execution
! A program can deal with an exception in one of three ways
ignore it (“uncaught” exception – abnormal termination)
handle it where it occurs
handle it an another place in the program
! The manner in which an exception is processed
is an important design consideration
1-2
10.2 – Zero.java
//********************************************************************
// Zero.java Java Foundations
// Demonstrates an uncaught exception.
//********************************************************************
public class Zero
{
//-----------------------------------------------------------------
// Deliberately divides by zero to produce an exception.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int numerator = 10;
int denominator = 0;
System.out.println ("Before the attempt to divide by zero.");
System.out.println (numerator / denominator);
System.out.println ("This text will not be printed.");
}
}
10.3 – The try Statement
! To handle an exception, the line
that throws the exception is
executed within a try block
! A try block is followed by one or
more catch clauses
! Each catch clause has an
associated exception type and is
called an exception handler
! When an exception occurs,
processing continues
at the first catch clause that
matches the exception type
1-4
// here is code that
// should generate no exceptions
try {
// code to monitor
// several possible things
// that can go wrong
// goes here
}
catch (ExceptionTypeA ex) {
//handler for ExceptionTypeA
}
catch (ExceptionTypeB ex) {
//handler for ExceptionTypeB
}
// after a catch, code continues here
pf3
pf4

Partial preview of the text

Download Exception Handling, Zero Java - Lecture Slides | CS 230 and more Exams Data Structures and Algorithms in PDF only on Docsity!

10.1 – Exceptions vs Errors

An exception is an object describing unusual or erroneous situation

 Division by 0 in computing expression (ArithmeticException)

 Array index out of bounds (IndexOutOfBoundsException)

 Null pointer cannot be followed (NullPointerException)

 I/O problems (e.g., no space on disk to save file, file not found)

 No permissions to do something (e.g., save a file)

Exceptions are thrown by a program,

and may be caught and handled by another part of the program

A program can be separated into a normal execution flow and

an exception execution flow

(An error is also an object,

but it represents a unrecoverable situation and should not be caught)

10.1 – Exception Handling

Java has a predefined set of exceptions and errors

that can occur during execution

A program can deal with an exception in one of three ways

 ignore it (“ uncaught ” exception – abnormal termination)

 handle it where it occurs

 handle it an another place in the program

The manner in which an exception is processed

is an important design consideration

10.2 – Zero.java

// Zero.java Java Foundations // //******************************************************************** Demonstrates an uncaught exception. public class Zero { //----------------------------------------------------------------- // Deliberately divides by zero to produce an exception. //----------------------------------------------------------------- public static void main (String[] args) { int numerator = 10; int denominator = 0; System.out.println ("Before the attempt to divide by zero."); System.out.println (numerator / denominator); System.out.println ("This text will not be printed."); } }

10.3 – The try Statement

To handle an exception, the line

that throws the exception is

executed within a try block

A try block is followed by one or

more catch clauses

Each catch clause has an

associated exception type and is

called an exception handler

When an exception occurs,

processing continues

at the first catch clause that

matches the exception type

// here is code that // should generate no exceptions try { // code to monitor // several possible things // that can go wrong // goes here } catch (ExceptionTypeA ex) { //handler for ExceptionTypeA } catch (ExceptionTypeB ex) { //handler for ExceptionTypeB } // after a catch, code continues here

10.3 – ProductCodes.java

System.out.print ("Enter product code (STOP to quit): "); code = scan.nextLine(); while (!code.equals ("STOP")) { try { zone district = code.charAt(9); = Integer.parseInt(code.substring(3, 7)); valid++; if (zone == 'R' && district > 2000) banned++; } catch (StringIndexOutOfBoundsException exception) { System.out.println ("Improper code length: " + code); } catch (NumberFormatException exception) { System.out.println ("District is not numeric: " + code); } System.out.print ("Enter product code (STOP to quit): "); code = scan.nextLine(); }

10.3 – The finally Clause

A try statement can have an optional clause following the catch

clauses, designated by the reserved word finally

The statements in the finally clause always are executed

If no exception is generated, the statements in the finally clause

are executed after the statements in the try block complete

If an exception is generated, the statements in the finally clause

are executed after the statements in the appropriate catch

clause complete

10.5 – EC Hierarchy

Classes that define exceptions are

related by inheritance, forming an

exception class hierarchy

All error and exception classes are

descendents of the Throwable class

A programmer can define an

exception by extending the

Exception class or one of its

descendants

The parent class used depends on

how the new exception will be used

1-

10.5 – An exception is either checked or unchecked

A checked exception must

either

 be caught by a method, or

 be listed in the throws clause of

any method that may throw or

propagate it

A throws clause is appended

to the method header

The compiler will issue error

if a checked exception is not

caught or asserted in a

throws clause

1-

An unchecked exception does

not require explicit handling

The only unchecked exceptions

in Java are objects of type

RuntimeException

or any of its descendants

Errors are similar to

RuntimeException and its

descendants in that

 Errors should not be caught

 Errors do not require a throws

clause

Displaying the contents of a web page

/* Read in the contents of a web page line by line,

  • and print out each line after it is read in.
  • Stop when the end of the web page is reached. */ public static void displayWebPage (String urlName) { try { URL u = new URL(urlName); BufferedReader reader = new BufferedReader( new InputStreamReader(u.openStream())); String line = reader.readLine(); // Read the first line of the web page while (line != null) { // Line becomes null at end of web page System.out.println(line); line = reader.readLine(); // Read the next line of the web page } reader.close(); } catch (IOException ex) { System.out.println(ex); } }

Displaying contents read in from

keyboard

/* Read in lines of text from the keyboard,

  • and print out each line after it is read in.
  • Stop when the user enters “quit”. */ public static void displayKeyboardInput () { try { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); String line = “”; while (!line.equals(“quit”)) { // Stop when user enters “quit” line = reader.readLine(); // Read the next line of keyboard input System.out.println(line); } reader.close(); } catch (IOException ex) { System.out.println(ex); } }

FileIO Operations in Java

import java.io.*; // Java I/O package

import java.net.*; // Java web package

public class FileOps {

public static void main(String[] args) {

if ((args.length == 2) && (args[0].equals("displayFile"))) {

displayFile(args[1]);

Copying a File

/* Copies an input file to an output file.

  • Displays an error message if the output file cannot be created. */ public static void copyFile (String inFileName, String outFileName) { try { BufferedReader reader = new BufferedReader(new FileReader(inFileName)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFileName)); String line = reader.readLine(); // Read first line of the input file while (line != null) { // Line becomes null at end of file writer.write(line + '\n'); // Write line to output file line = reader.readLine(); // Read next line of the input file } reader.close(); writer.close(); } catch (IOException ex) { System.out.println(ex); // Handle file-not-found } }