Top Banner
MSc IT Programming Methodology (2)
101

MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Dec 16, 2015

Download

Documents

Liliana Veil
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

MSc IT

Programming Methodology (2)

Page 2: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

THROWS an EXCEPTION

Errors?

Page 3: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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.

Exceptions

Page 4: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Pre-defined exception classes in Java

Page 5: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

Page 6: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

Exception Error

Page 7: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

Exception Error

RuntimeExceptionIOException

Page 8: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

FileNotFoundException

Exception Error

RuntimeExceptionIOException

Page 9: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Page 10: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Page 11: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Page 12: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Unchecked

Page 13: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Unchecked

Page 14: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Checked

Page 15: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Java Compiler

RuntimeException

NumberFormatException

IOException

FileNotFoundException WARNING!

Page 16: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Handling exceptions: an example

Page 17: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

code for this method.

Page 18: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Outline TestException class

public class TestException{

public static int getInteger(){

// code for method goes here}

}

Page 19: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

The read method of System.in

Page 20: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

"hello"

System.in.read( [ ] )

array of bytes

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

Page 21: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Coding the getInteger method

Page 22: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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);

The read method may throw a checked IOException

Page 23: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Dealing with exceptions..

Page 24: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

Page 25: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

IOException!

Page 26: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

catch

Page 27: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

IOException!

Page 28: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

throw

Page 29: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

IOException!

read

throw

Page 30: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

IOException!

read

Page 31: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

catch

Page 32: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

IOException!

read

Page 33: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

throw

Page 34: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

IOException!

getInteger

read

throw

Page 35: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Claiming an exception

Page 36: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 }}

This method will pass on the IOException error.

Page 37: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 38: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

IOException!

getInteger

read

throw

Page 39: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

IOException!

getInteger

read

Page 40: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

catch

Page 41: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

IOException!

getInteger

read

Page 42: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

main

getInteger

read

throw

PROGRAM CRASH!!!!

Page 43: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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"); } }}

Page 44: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 45: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

A Stack Trace

Page 46: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 47: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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.

Page 48: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 49: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 50: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 51: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Test Run of ApititudeTest2

Enter aptitude test score: 12w

You entered an invalid number!Goodbye

Page 52: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 53: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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"); }}

Generates a NumberFormatException

Page 54: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 55: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 56: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 57: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Exceptions in GUI applications

room should be a number

Page 58: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Using exceptions in your own classes

Page 59: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Look back at the Bank constructor:

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

A negative value would cause a NegativeArraySizeException.

Page 60: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Making use of exceptions: a first attempt

Page 61: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Reveals that we are using an array.

Page 62: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Making use of exceptions: a second attempt

Page 63: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 64: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Testing for the exception

Page 65: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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 66: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Creating your own exception classes

Page 67: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

Page 68: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Throwable

NumberFormatException ArrayIndexOutOfBoundsException

FileNotFoundException

Exception Error

RuntimeExceptionIOException

IllegalArgumentException IndexOutOfBoundsException

NegativeSizeException

Page 69: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 70: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Amending the Bank constructor

Page 71: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 72: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 73: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 74: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Testing for the NegativeSizeException

Page 75: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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(); } // rest of code here }}

Page 76: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Re-throwing exceptions

Page 77: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 78: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 79: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 80: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 81: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

Page 82: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

Practical Work

Page 83: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

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

int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); System.out.println("End of program" ); } private static int getPosition() { System.out.println("Enter array position to display"); String positionEntered = EasyScanner.nextString(); return Integer.parseInt(positionEntered); } private static void display (int[ ] arrayIn, int posIn) { System.out.println("Item at this position is: " + arrayIn[posIn]); }}

return Integer.parseInt(positionEntered);

System.out.println("Item at this position is: " + arrayIn[posIn]);

NumberFormatException

ArrayIndexOutOfBoundsException

Page 84: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

a) Re-write main so that it catches any exceptions it may now throw by displaying a message on the screen indicating the exception thrown.

Page 85: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){

int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); System.out.println("End of program" );}

Page 86: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){ try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); }

System.out.println("End of program" );}

// catches go here

Page 87: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

b) Add an additional catch clause in main to catch any unaccounted for exceptions (within this catch clause print out the stack trace of the exception).

Page 88: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){ try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); }

System.out.println("End of program" );}

// old catches as before

Page 89: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){ try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); }

System.out.println("End of program" );}

// old catches as before

// add additional catch clause

Catches all exceptions not caught so far.

Page 90: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

c) Create your own exception class InvalidPositionException (make this a checked exception).

Page 91: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public class InvalidPositionException{

}

Page 92: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public class InvalidPositionException{

}

Make this a checked exception

Page 93: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public class InvalidPositionException{

}

extends Exception

Page 94: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public class InvalidPositionException{

}

extends Exception

// add two constructors here

Page 95: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

d) Re-write the display method so that it throws the InvalidPositionException from a catch block.

Page 96: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

private static void display (int[ ] arrayIn, int posIn){ System.out.println("Item at this position is: " + arrayIn[posIn]);}

Page 97: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

private static void display (int[ ] arrayIn, int posIn) throws InvalidPositionException { System.out.println("Item at this position is: " + arrayIn[posIn]);}

Page 98: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

private static void display (int[ ] arrayIn, int posIn) throws InvalidPositionException { try { System.out.println("Item at this position is: " + arrayIn[posIn]); } catch ( ? ) { // code here } }

Page 99: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

e) Re-write main to take account of this amended display method.

Page 100: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){ try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); }

System.out.println("End of program" );}

// old catches

Page 101: MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?

public static void main(String[ ] args){ try { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); }

System.out.println("End of program" );}

// modify catches so this new exception is caught