cen 414 java programmingenformatik.cu.edu.tr/java-2/week3-java.pdf · exception-handling overview...

42
Slides are modified from original slides of Y. Daniel Liang CEN 414 Java Programming Week 3 – Exception Handling and Text I/O Dr. H. Esin ÜNAL SPRING 2020

Upload: others

Post on 23-May-2020

8 views

Category:

Documents


0 download

TRANSCRIPT

Slides are modified from original slides of Y. Daniel Liang

CEN 414Java Programming

Week 3 – Exception Handling and Text I/O

Dr. H. Esin ÜNALSPRING

2020

Introduction

Exception handling enables a program to deal withexceptional situations and continue its normal execution.

Runtime errors occur while a program is running if theJVM detects an operation that is impossible to carry out:

ArrayIndexOutOfBoundsException: If you access an arrayusing an index that is out of bounds.

InputMismatchException: If you enter a double value whenyour program expects an integer.

In Java, runtime errors are thrown as exceptions.

An exception is an object that represents an error or acondition that prevents execution from proceedingnormally.

Week 3 CEN 414 Java Programming - Spring 2020 2

Exception-Handling Overview

Exceptions are thrown from a method. The caller of themethod can catch and handle the exception (many library

methods throw exceptions, like nextInt() method in Scanner class).

You see the advantages of using exception handling inthese examples. It enables a method to throw anexception to its caller. Without this capability, a methodmust handle the exception or terminate the program.

Week 3 CEN 414 Java Programming - Spring 2020

EXAMPLE 1 EXAMPLE 2

http://www.cs.armstrong.edu/liang/intro10e/html/QuotientWithException.html

http://www.cs.armstrong.edu/liang/intro10e/html/InputMismatchExceptionDemo.html

3

Exception-Handling Overview

The value thrown (eg. new ArithmeticException("Divisor cannot be zero"))

is called an exception. It is an object created from anexception class (eg. java.lang.ArithmeticException class).

The execution of a throw statement is called throwingan exception (eg. throw new ArithmeticException("Divisor connot be zero").

The statement for invoking the method is contained in atry block and a catch block.

The try block contains the code that is executed in normalcircumstances.

The exception is caught by the catch block. The code in thecatch block is executed to handle the exception.

Week 3 CEN 414 Java Programming - Spring 2020 4

Exception-Handling

Steps

Week 3 CEN 414 Java Programming - Spring 2020

When an exception is thrown from the try block, the normal execution flow is interrupted.

If there is a catch block that can catch the thrownexception, the code in the block is executed.

Afterward, the statement after the catch block is executed. The program control doesn’t return to thethrow statement.

5

Templatefor

try-throw-catch

try {

Code to run;

A statement or a method that may throw an exception;

More code to run;

}

catch (type ex) {

Code to process the exception;

}

Week 3 CEN 414 Java Programming - Spring 2020

An exception may be thrown directly by using a throwstatement in a try block, or by invoking a method that maythrow an exception.

6

Exception Types

The Throwable class is the root of exception classes. All Java exception classes inherit directlyor indirectly from Throwable. You can create your own exception classes by extendingException or a subclass of Exception.

LinkageError

Error

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Many more classes

Many more classes

Many more classes

IllegalArgumentException

Week 3 CEN 414 Java Programming - Spring 2020 7

System Errors

System errors are thrown by JVM and represented in the Error class. The Error classdescribes internal system errors. Such errors rarely occur. If one does, there is little you cando beyond notifying the user and trying to terminate the program gracefully.

LinkageError

Error

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Many more classes

Many more classes

Many more classes

IllegalArgumentException

Week 3 CEN 414 Java Programming - Spring 2020 8

Exceptions

Exception describes errors caused by your program and external circumstances. Theseerrors can be caught and handled by your program (eg. Attempt to use a class that doesn’texist, invalid input, opening a nonexistent file).

LinkageError

Error

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Many more classes

Many more classes

Many more classes

IllegalArgumentException

Week 3 CEN 414 Java Programming - Spring 2020 9

Runtime Exceptions

RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors (eg. dividing an integer by zero, attempt to access anobject through a null reference variable, a method is passed an argument that is illegal) .

LinkageError

Error

Throwable

ClassNotFoundException

VirtualMachineError

IOException

Exception

RuntimeException

Object

ArithmeticException

NullPointerException

IndexOutOfBoundsException

Many more classes

Many more classes

Many more classes

IllegalArgumentException

Week 3 CEN 414 Java Programming - Spring 2020 10

Checked Exceptions

vsUnchecked Exceptions

RuntimeException, Error and their subclasses are known

as unchecked exceptions.

All other exceptions are known as checked exceptions,

meaning that the compiler forces the programmer to

check and deal with them in a try-catch block or declare

it in the method header.

Checked exceptions are checked at compile-time.

Week 3 CEN 414 Java Programming - Spring 2020 11

Unchecked Exceptions

In most cases, unchecked exceptions reflect programming logic

errors that are not recoverable.

For example, a NullPointerException is thrown if you access an

object through a reference variable before an object is assigned to

it; an IndexOutOfBoundsException is thrown if you access an

element in an array outside the bounds of the array. These are the

logic errors that should be corrected in the program.

Unchecked exceptions can occur anywhere in the program.

Unchecked exceptions are not checked at compile-time, but

they are checked at runtime.

To avoid cumbersome overuse of try-catch blocks, Java does not

mandate you to write code to catch unchecked exceptions.

Week 3 CEN 414 Java Programming - Spring 2020 12

Declaring, Throwing, and

Catching Exceptions

Java’s exception-handling model is based on three

operations:

declaring an exception

throwing an exception

catching an exception

Week 3 CEN 414 Java Programming - Spring 2020 13

Declaring Exceptions

Every method must state the types of checkedexceptions it might throw. This is known as declaringexceptions.

Java does not require that you declare Error andRuntimeException (unchecked exceptions) explicitly inthe method. However, all other exceptions thrown by themethod must be explicitly declared in the methodheader so that the caller of the method is informed ofthe exception.

public void myMethod() throws IOException

public void myMethod() throws Exception1,..., ExceptionN

Week 3 CEN 414 Java Programming - Spring 2020 14

Throwing Exceptions

When the program detects an error, the program can create aninstance of an appropriate exception type and throw it. This isknown as throwing an exception. Here is an example,

OR

TheException ex = new TheException();throw ex;

throw new TheException();

NOTE: In general, each exception class in the Java API has at least two constructors: a no-arg constructor, and a constructor with a String argument that describes the exception.This argument is called the exception message, which can be obtained usinggetMessage()

/** Set a new radius */public void setRadius(double newRadius) throws IllegalArgumentException {if (newRadius >= 0)radius = newRadius;

elsethrow new IllegalArgumentException("Radius cannot be negative");

}Week 3 CEN 414 Java Programming - Spring 2020 15

When an exception is thrown, it can be caught andhandled in a try-catch block, as follows:

If no exceptions arise during the execution of the tryblock, the catch blocks are skipped.

Catching Exceptions

try {statements; // Statements that may throw exceptions

}catch (Exception1 exVar1) {

handler for exception1;}catch (Exception2 exVar2) {

handler for exception2;}...catch (ExceptionN exVar3) {

handler for exceptionN;}

Week 3 CEN 414 Java Programming - Spring 2020 16

Catching Exceptions

If one of the statements inside the try block throws an exception, Java skipsthe remaining statements in the try block and starts the process of findingthe code to handle the exception.

The code that handles the exception is called the exception handler; it isfound by propagating the exception backward through a chain of methodcalls, starting from the current method.

Each catch block is examined in turn, from first to last, to see whether thetype of the exception object is an instance of the exception class in the catchblock.

If so, the exception object is assigned to the variable declared, and the code in thecatch block is executed.

If no handler is found, Java exits this method, passes the exception to the methodthat invoked the method, and continues the same process to find a handler.

If no handler is found in the chain of methods being invoked, the programterminates and prints an error message on the console.

The process of finding a handler is called catching an exception.

Week 3 CEN 414 Java Programming - Spring 2020 17

An Examplefor

Catching Exceptions

Week 3 CEN 414 Java Programming - Spring 2020

• If the exception type is Exception3, it is caught by the catch block for handling exception ex3 inmethod2. statement5 is skipped, and statement6 is executed.

• If the exception type is Exception2, method2 is aborted, the control is returned to method1, and theexception is caught by the catch block for handling exception ex2 in method1. statement3 is skipped,and statement4 is executed.

• If the exception type is Exception1, method1 is aborted, the control is returned to the main method,and the exception is caught by the catch block for handling exception ex1 in the main method.statement1 is skipped, and statement2 is executed.

• If the exception type is not caught in method2, method1, or main, the program terminates, andstatement1 and statement2 are not executed.

18

NOTE:Order

of exceptionhandlers

The order in which exceptions are specified in catch blocks isimportant. A compile error will result if a catch block for asuperclass type appears before a catch block for a subclasstype.

For example, the ordering in (a) on the next page iserroneous, because RuntimeException is a subclass ofException. The correct ordering should be as shown in (b).

Week 3 CEN 414 Java Programming - Spring 2020 19

NOTE:Catch or Declare Checked

Exceptions

Java forces you to deal with checked exceptions. If a methoddeclares a checked exception (i.e., an exception other than Error orRuntimeException), you must invoke it in a try-catch block or declareto throw the exception in the calling method. For example, supposethat method p1 invokes method p2 and p2 may throw a checkedexception (e.g., IOException), you have to write the code as shownin (a) or (b).

Week 3 CEN 414 Java Programming - Spring 2020

void p2() throws IOException {if (a file does not exist) {

throw new IOException("File does not exist");}...

}

20

NOTE:Multi-catch

You can use multi-catch feature to simplify coding for theexceptions with the same handling code.

The syntax is:

Each exception type is separated from the next with avertical bar (|).

If one of the exceptions is caught, the handling code isexecuted.

Week 3 CEN 414 Java Programming - Spring 2020

catch (Exception1 | Exception2 | ... | Exceptionk ex) {// Same code for handling these exceptions}

21

Example: Declaring,

Throwing, and Catching

Exceptions

This example demonstrates declaring,throwing, and catching exceptions bymodifying the setRadius method in the Circleclass defined before.

The new setRadius method throws anexception if radius is negative.

Week 3 CEN 414 Java Programming - Spring 2020

Test Circle with Exception

Circle with Exception

http://www.cs.armstrong.edu/liang/intro10e/html/TestCircleWithException.html

http://www.cs.armstrong.edu/liang/intro10e/html/CircleWithException.html

22

The finally

Clause

try { statements;

}catch(TheException ex) { handling ex;

}finally { finalStatements;

}

Week 3 CEN 414 Java Programming - Spring 2020

The finally clause is always executed regardless whether anexception occurred or not.

23

RethrowingExceptions

try { statements;

}catch (TheException ex) { perform operations before exits;throw ex;

}

Week 3 CEN 414 Java Programming - Spring 2020

Java allows an exception handler to rethrow the exceptionif the handler cannot process the exception or simplywants to let its caller be notified of the exception.

24

When to Throw and Use

Exceptions

An exception occurs in amethod. If you want theexception to be processed byits caller, you should create anexception object and throw it.If you can handle theexception in the methodwhere it occurs, there is noneed to throw it.

When should you use the try-catch block in the code? Youshould use it to deal withunexpected error conditions.Do not use it to deal withsimple, expected situations.

Week 3 CEN 414 Java Programming - Spring 2020

try {

System.out.println(refVar.toString());

}

catch (NullPointerException ex) {

System.out.println("refVar is null");

}

if (refVar != null)

System.out.println(refVar.toString());

else

System.out.println("refVar is null");

25

Defining Custom

Exception Classes

Define custom exception classes by extending Exceptionor a subclass of Exception, such as IOException.

In our circle class defined before (Slide 22) the setRadiusmethod throws an exception if the radius is negative.Suppose you wish to pass the radius to the handler. Inthat case you have to create a custom exception class.

Week 3 CEN 414 Java Programming - Spring 2020

Custom Exception Class

Circle with Exception

Test Circle with Exception

http://www.cs.armstrong.edu/liang/intro10e/html/InvalidRadiusException.html

http://www.cs.armstrong.edu/liang/intro10e/html/CircleWithRadiusException.html

http://www.cs.armstrong.edu/liang/intro10e/html/TestCircleWithRadiusException.html

26

The File Class

The File class contains the methods for obtaining theproperties of a file/directory and for renaming anddeleting a file/directory.

However, it does not contain the methods for readingand writing file contents.

The filename is a string. The File class is a wrapper classfor the file name and its directory path.

For example, new File("c:\\book") creates a File object for the directory

c:\book

new File("c:\\book\\test.dat") creates a File object for the filec:\book\test.dat

Week 3 CEN 414 Java Programming - Spring 2020 27

Obtaining file properties

and manipulating file

Week 3 CEN 414 Java Programming - Spring 2020 28

NOTE

1. The directory separator for Windows is a backslash (\).The backslash is a special character in Java and shouldbe written as \\ in a string literal

2. Constructing a File instance does not create a file onthe machine. You can create a File instance for any filename regardless whether it exists or not. You caninvoke the exists() method on a File instance to checkwhether the file exists.

3. Do not use absolute file names in your program. If youuse a file name such as c:\\book\\ Welcome.java, itwill work on Windows but not on other platforms. Youshould use a file name relative to the current directory.

Week 3 CEN 414 Java Programming - Spring 2020 29

Example

Week 3 CEN 414 Java Programming - Spring 2020

import java.io.*;

public class TestFileClass {

public static void main(String[] args) {

File file = new File("image/us.gif");System.out.println("Does it exist? " + file.exists());System.out.println("The file has " + file.length() + " bytes");System.out.println("Can it be read? " + file.canRead());System.out.println("Can it be written? " + file.canWrite());System.out.println("Is it a directory? " + file.isDirectory());System.out.println("Is it a file? " + file.isFile());System.out.println("Is it absolute? " + file.isAbsolute());System.out.println("Is it hidden? " + file.isHidden());System.out.println("Absolute path is " + file.getAbsolutePath());System.out.println("Last modified on " +

new java.util.Date(file.lastModified()));}

}

An example on how to create a File object and use the methods inthe File class to obtain its properties.

30

Example

Week 3 CEN 414 Java Programming - Spring 2020

Sample run of the program

on Windows

Sample run of the program

on UNIX

31

Text File I/O

A File object encapsulates the properties of a file or a

path, but does not contain the methods for

reading/writing data from/to a file.

In order to perform I/O, you need to create objects using

appropriate Java I/O classes. The objects contain the

methods for reading/writing data from/to a file.

This section introduces how to read/write strings and

numeric values from/to a text file using the Scanner and

PrintWriter classes.

There are two types of files: text and binary. Text files are

essentially characters on disk. Now we are going to work

with text files.Week 3 CEN 414 Java Programming - Spring 2020 32

Writing Data Using

PrintWriter

The java.io.PrintWriter class can be used to create a file and write data to a textfile.

First, you have to create a PrintWriter object for a text file as follows:

Then, you can invoke the print, println, and printf methods on the PrintWriterobject to write data to a file.

Week 3 CEN 414 Java Programming - Spring 2020

PrintWriter output = new PrintWriter(filename);

33

Example

import java.io.*;public class WriteData {

public static void main(String[] args) throws IOException {File file = new File("scores.txt");if (file.exists()) {

System.out.println("File already exists");System.exit(0);

}

// Create a filePrintWriter output = new PrintWriter(file);

// Write formatted output to the fileoutput.print("John T Smith ");output.println(90);output.print("Eric K Jones ");output.println(85);

// Close the fileoutput.close();

}}

Week 3 CEN 414 Java Programming - Spring 2020

The close() method must be usedto close the file. If this method isnot invoked, the data may not besaved properly in the file.

If the file already exists, thecurrent content in the file will bediscarded without verifying withthe user.

34

Closing Resources

Automatically Using

try-with-resources

Programmers often forget to close the file. JDK 7 providesthe followings try-with-resources syntax that automaticallycloses the files.

Week 3 CEN 414 Java Programming - Spring 2020

try (declare and create resources) {

Use the resource to process the file;

}

try (// Create a filePrintWriter output = new PrintWriter(file);) {

// Write formatted output to the fileoutput.print("John T Smith ");output.println(90);output.print("Eric K Jones ");output.println(85);

}

35

Reading Data Using

Scanner

To read from a file, create a Scanner for a file, as follows:

A Scanner breaks its input into tokens delimited bywhitespace characters.

Week 3 CEN 414 Java Programming - Spring 2020 36

Scanner input = new Scanner(new File(filename));

Example

import java.util.Scanner;İmport java.io.*;

public class ReadData {public static void main(String[] args) throws Exception {

// Create a File instanceFile file = new File("scores.txt");

// Create a Scanner for the fileScanner input = new Scanner(file);

// Read data from a filewhile (input.hasNext()) {String firstName = input.next();String mi = input.next();String lastName = input.next();int score = input.nextInt();System.out.println(firstName + " " + mi + " " + lastName + " " + score);

}

// Close the fileinput.close();

}}

Week 3 CEN 414 Java Programming - Spring 2020 37

Problem: Replacing Text

Write a class named ReplaceText that replaces a string in a textfile with a new string. The filename and strings are passed ascommand-line arguments as follows:

java ReplaceText sourceFile targetFile oldString newString

For example, invoking

java ReplaceText FormatString.java t.txt StringBuilder StringBuffer

replaces all the occurrences of StringBuilder by StringBuffer inFormatString.java and saves the new file in t.txt.

Week 3 CEN 414 Java Programming - Spring 2020 38

Replace Text

http://www.cs.armstrong.edu/liang/intro10e/html/ReplaceText.html

Reading Data from the Web

Just like you can read data from a file on your computer,you can read data from a file on the Web.

For an application program to read data from a URL, youfirst need to create a URL object using the java.net.URLclass with this constructor:

Week 3 CEN 414 Java Programming - Spring 2020 39

public URL(String spec) throws MalformedURLException

Reading Data from the Web

For example the following statement creates a URL object;

try {

URL url = new URL("http://www.google.com/index.html");

}

catch (MalformedURLException ex) {

ex.printStackTrace();

}

After a URL object is created, you can use the openStream() methoddefined in the URL class to open an input stream and use thisstream to create a Scanner object as follows:

Scanner input = new Scanner(url.openStream());

Week 3 CEN 414 Java Programming - Spring 2020 40

Read file from URL

http://www.cs.armstrong.edu/liang/intro10e/html/ReadFileFromURL.html

Case Study: Web Crawler

This case study develops a program that travels the Webby following hyperlinks.

The program follows the URLs to traverse the Web. Toavoid that each URL is traversed only once, the programmaintains two lists of URLs. One list stores the URLspending for traversing and the other stores the URLs thathave already been traversed.

Week 3 CEN 414 Java Programming - Spring 2020 41

Case Study: Web Crawler

The algorithm for this program can be described as follows:

Add the starting URL to a list named listOfPendingURLs;

while listOfPendingURLs is not empty {

Remove a URL from listOfPendingURLs;

if this URL is not in listOfTraversedURLs {

Add it to listOfTraversedURLs;

Display this URL;

Read the page from this URL and for each URL contained in the page {

Add it to listOfPendingURLs if it is not in listOfTraversedURLs;

}

}

}

Week 3 CEN 414 Java Programming - Spring 2020 42

Web Crawler

http://www.cs.armstrong.edu/liang/intro10e/html/WebCrawler.html