Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "MSc IT Programming Methodology (2). THROWS an EXCEPTION Errors?"— Presentation transcript:

1 MSc IT Programming Methodology (2)

2 THROWS an EXCEPTION Errors?

3 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

4 Pre-defined exception classes in Java

5 Throwable

6 Exception Error

7 Throwable Exception Error RuntimeException IOException

8 Throwable FileNotFoundException Exception Error RuntimeException IOException

9 Throwable FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

10 Throwable NumberFormatException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

11 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

12 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Unchecked

13 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Unchecked

14 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException Checked

15 Java Compiler RuntimeException NumberFormatException IOException FileNotFoundException WARNING!

16 Handling exceptions: an example

17 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.

18 Outline TestException class public class TestException { public static int getInteger() { // code for method goes here } }

19 The read method of System.in

20 "hello" System.in.read( [ ] ) array of bytes 104,101,108, 111,13,10

21 Coding the getInteger method

22 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); TThe read method may throw a checked IOException

23 Dealing with exceptions..

24 main getInteger read

25 main getInteger read IOException!

26 main getInteger read catch

27 main getInteger read IOException!

28 main getIntegerread throw

29 main getInteger IOException! read throw

30 main getInteger IOException! read

31 main getIntegerread catch

32 main getInteger IOException! read

33 maingetIntegerread throw

34 main IOException! getIntegerread throw

35 Claiming an exception

36 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.

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

38 main IOException! getIntegerread throw

39 main IOException! getIntegerread

40 main getIntegerread catch

41 main IOException! getIntegerread

42 maingetIntegerread throw PROGRAM CRASH!!!!

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

44 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

45 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

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

47 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.

48 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

49 Some methods of the Exception class methoddescription printStackTrace prints (onto the console) a stack trace of the exception toString returns a detailed error message getMessage returns a summary error message

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

51 Test Run of ApititudeTest2 Enter aptitude test score:12w You entered an invalid number! Goodbye

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

53 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

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

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

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

57 Exceptions in GUI applications room should be a number

58 Using exceptions in your own classes

59 Look back at the Bank constructor: public Bank(int sizeIn) { list = new BankAccount[sizeIn]; total = 0; } A negative value would cause a NegativeArraySizeException.

60 Making use of exceptions: a first attempt

61 public Bank(int sizeIn) throws NegativeArraySizeException { list = new BankAccount[sizeIn]; total = 0; } Reveals that we are using an array.

62 Making use of exceptions: a second attempt

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

64 Testing for the exception

65 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

66 Creating your own exception classes

67 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException

68 Throwable NumberFormatException ArrayIndexOutOfBoundsException FileNotFoundException Exception Error RuntimeException IOException IllegalArgumentException IndexOutOfBoundsException NegativeSizeException

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

70 Amending the Bank constructor

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

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

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

74 Testing for the NegativeSizeException

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

76 Re-throwing exceptions

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

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

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

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

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

82 Practical Work

83 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

84 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.

85 public static void main(String[ ] args) { int[ ] someArray = {12,9,3,11}; int position = getPosition(); display (someArray, position); System.out.println("End of program" ); }

86 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

87 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).

88 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

89 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.

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

91 public class InvalidPositionException { }

92 public class InvalidPositionException { } Make this a checked exception

93 public class InvalidPositionException { } extends Exception

94 public class InvalidPositionException { } extends Exception // add two constructors here

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

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

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

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

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

100 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

101 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


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

Similar presentations


Ads by Google