exceptions by the end of this lecture you should be able to: explain the term exception; distinguish...

31
Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in Java; claim an exception using a throws clause throw an exception using a throw command ; catch an exception in a try catch block; define and use your own exception classes.

Upload: arline-fields

Post on 05-Jan-2016

230 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Exceptions

By the end of this lecture you should be able to:

• explain the term exception;

• distinguish between checked and unchecked exception classes in Java;

• claim an exception using a throws clause

• throw an exception using a throw command ;

• catch an exception in a try catch block;

• define and use your own exception classes.

Page 2: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Introduction

THROWS an exception

If an error occurs

Java run-time environment

Page 3: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Pre-defined exception classes in Java

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Page 4: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Checked and unchecked exceptions

Java Compiler

RuntimeException

NumberFormatException

IOException

FileNotFoundException ERROR

Page 5: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Handling exceptions: an example

public class AptitudeTest{ public static void main (String[] args) { int score; System.out.print("Enter aptitude test score: "); score = TestException.getInteger( ); // test score here }}

A program that allows a user to enter an aptitude test mark at the keyboard.

Page 6: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Outline TestException class

public class TestException{

public static int getInteger(){

// code for method goes here}

}

Page 7: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

The read method of System.in

"hello"

System.in.read( [ ] )

array of bytes

104,101,108,108,111,13, 10

Page 8: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Coding the getInteger method

This is a first attempt, it will not compile!

byte [] buffer = new byte[512];

System.in.read(buffer);

String s = new String (buffer);

s = s.trim();

int num = Integer.parseInt(s);

return num;

System.in.read(buffer);

System.in may throw a checked IOException

Page 9: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Dealing with exceptions

Whenever a method that throws a checked exception, the Java compiler insists that we acknowledge this exception in some way.

There are always two ways to deal with an exception:

1. Deal with the exception within the method by catching it;

2. Pass on the exception out of the method by claiming it.

Page 10: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Claiming an exception

Claiming an exception refers to a given method having been marked to indicate that it will pass on an exception object that it might generate.

To claim an exception we add a throws clause to our method header :

import java.io.*public class TestException{ private static int getInteger( ) throws IOException {

// as before } }

Page 11: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Revisiting the AptitudeTest class

public class AptitudeTest

{

public static void main (String[] args)

{

int score;

System.out.print("Enter aptitude test score: ");

score = TestException.getInteger( );

// test score here

}

}

score = TestException.getInteger( );

Page 12: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

import java.io.*; public class AptitudeTest{ public static void main (String[] args) throws IOException { int score; System.out.print("Enter aptitude test score: "); score = TestException.getInteger( ); if (score >= 50) { System.out.println("You have a place on the course!"); } else { System.out.println("Sorry, you failed your test"); } }}

Fixing the problem

Page 13: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

A test run

Enter aptitude test score:

java.lang.NumberFormatException: 12w

at java.lang.Integer.parseInt(Integer.java:418)

at java.lang.Integer.parseInt(Integer.java:458)

at TestException.getInteger(TestException.java:10)

at AptitudeTest.main(AptitudeTest.java:11

12w

Page 14: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

NumberFormatException

byte [] buffer = new byte[512];

System.in.read(buffer);

String s = new String (buffer);

s = s.trim();

int num = Integer.parseInt(s);

return num;

int num = Integer.parseInt(s);

Page 15: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Catching an exception

In order to trap the exception object in a catch block you must surround the code that could generate the exception in a try block.

methodthrow Exception

catch Exception

Page 16: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Syntax for using a try and catch block

try { // code that could generate an exception}catch (Exception e) { // action to be taken when an exception occurs}// other instructions could be placed here

Page 17: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Some methods of the Exception class

method description

printStackTrace prints (onto the console) a stack trace of the exception

toString returns a detailed error message

getMessage returns a summary error message

Page 18: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

import java.io.*;public class AptitudeTest2{ public static void main (String[] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }}

Page 19: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Test Run of ApititudeTest2

Enter aptitude test score: 12w

You entered an invalid number!Goodbye

Page 20: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

import java.io.*;public class AptitudeTest2{ public static void main (String[] args) { try { // as before score = TestException.getInteger( ); // as before } catch (NumberFormatException e) { System.out.println("You entered an invalid number!"); } catch (IOException e) { System.out.println(e); } System.out.println("Goodbye"); }}

Page 21: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

import java.io.*public class TestException{ private static int getInteger( ) throws IOException {

byte [] buffer = new byte[512]; System.in.read(buffer); String s = new String (buffer); s = s.trim(); int num = Integer.parseInt(s); return num;

} }

Page 22: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Exceptions in GUI applications

room should be a number

Page 23: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Using exceptions in your own classes

Look back at the Bank constructor:

public Bank(int sizeIn){ list = new BankAccount[sizeIn]; total = 0;}

A negative value would not be a valid array size

This would cause an exception in the program;

The name of the exception is NegativeArraySizeException.

Page 24: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Making use of exceptions: a first attempt

public Bank(int sizeIn) throws NegativeArraySizeException{ list = new BankAccount[sizeIn]; total = 0;}

Page 25: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Making use of exceptions: a second attempt

public Bank (int sizeIn) throws Exception{ if (sizeIn < 0) { throw new Exception ("cannot set a negative size"); } else { list = new BankAccount[sizeIn]; total = 0; }}

Page 26: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Testing for the exception

public class BankProgram{ public static void main(String[] args) { try { System.out.print(“Maximum number of accounts? “); size = EasyScanner.nextInt(); Bank myBank = new Bank(size);

// rest of code here } catch (Exception e) {

System.out.println(e.getMessage()); } } // other static methods here as before

Page 27: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Creating your own exception classes

public class NegativeSizeException extends Exception{ public NegativeSizeException () { super("cannot set a negative size"); } public NegativeSizeException (String message) { super (message); }}

Page 28: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Amending the Bank constructor

public Bank (int sizeIn) throws NegativeSizeException{ if (sizeIn < 0) { throw new NegativeSizeException(); } else { list = new BankAccount[sizeIn]; total = 0; }}

Page 29: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

public class BankProgram{ public static void main(String[] args) {

try{

System.out.print(“Maximum number of accounts? “); size = EasyScanner.nextInt(); Bank myBank = new Bank(size);

// rest of code here}catch (NegativeSizeException e){ System.out.println(e.getMessage());

System.out.println(“due to error in Bank constructor”); }

catch (Exception e) { System.out.println(“Some unforseen error”); e.printStackTrace(); } // other static methods here as before }}

Page 30: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Re-throwing exceptions

public Bank (int sizeIn) throws NegativeSizeException{ try { list = new BankAccount[sizeIn]; total = 0; } catch (NegativeArraySizeException e) {

throw new NegativeSizeException (); }}

Page 31: Exceptions By the end of this lecture you should be able to: explain the term exception; distinguish between checked and unchecked exception classes in

Documenting exceptions

/** Creates an empty collection of bank accounts * and fixes the maximum size of this collection * * @param sizeIn The maximum size of * the collection of bank * accounts * @throws NegativeSizeException If the collection is * sized with a negative * value */ public Bank (int sizeIn) throws NegativeSizeException{ // as before}