CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment: http://muele.mak.ac.ug office: block A, level 3, department of computer science alt. office: institute of open, distance, and elearning, room 2 Kizito (Makerere University) CSC 1214 March, 2018 1 / 24
Overview 1 Errors Exceptions Keywords Uncaught Exceptions try and catch throw throws finally Defining Own Exceptions Java s Exceptions Kizito (Makerere University) CSC 1214 March, 2018 2 / 24
Errors Introduction Errors You make mistakes when programming A program can have three types of errors 1 Compile-time errors: the compiler will find syntax errors and other basic problems If compile-time errors exist, an executable version of the program is not created 2 Run-time errors: a problem can occur during program execution, such as trying to divide by zero, which causes a program to terminate abnormally 3 Logical errors: a program may run, but produce incorrect results, perhaps using an incorrect formula Errors in programs are often called bugs Exceptions are a kind of run-time errors Kizito (Makerere University) CSC 1214 March, 2018 3 / 24
Exceptions Exceptions An Exception is an error event that can happen during the execution of a program and disrupts its normal flow Java provides a robust and object oriented way to handle exception scenarios, known as Java A Java exception is an object that describes an exceptional (i.e., error) condition that has occurred in a piece of code When an exceptional condition arises, the exception is caught and processed If an exception is ignored (not caught) by the program, the program will terminate abnormally and produce an appropriate message Exceptions can be generated by the Java run-time system, or by your code Exception handling is managed via five keywords: try, catch, throw, throws, and finally Kizito (Makerere University) CSC 1214 March, 2018 4 / 24
Keywords Keywords try, catch, throw, throws, finally Statements that you want to monitor for exceptions are contained within a try block Your code can catch this exception (using catch) and handle it in some manner System-generated exceptions are automatically thrown by the Java run-time system/environment (JRE) Exceptions are manually thrown using the keyword throw Any exception that is thrown out of a method must be specified as such by a throws clause Any code that absolutely must be executed before a method returns is put in a finally block Kizito (Makerere University) CSC 1214 March, 2018 5 / 24
Keywords Exception handling block try { // block of code to monitor for errors catch (ExceptionType1 exob) { // exception handler for ExceptionType1 catch (ExceptionType2 exob) { // exception handler for ExceptionType2 //... finally { // block of code to be executed before // try block ends Kizito (Makerere University) CSC 1214 March, 2018 6 / 24
Uncaught Exceptions Uncaught Exceptions 1. class Exc0 { 2. public static void main(string s[]) { 3. int d = 0; 4. int a = 42 / d; 5. 6. Output java.lang.arithmeticexception: at Exc0.main(Exc0.java:4) / by zero Kizito (Makerere University) CSC 1214 March, 2018 7 / 24
Uncaught Exceptions Output Uncaught Exceptions Error Reporting 1. class Exc1 { 2. static void subroutine() { 3. int d = 0; 4. int a = 10 / d; 5. 6. 7. public static void main(string args[]) { 8. Exc1.subroutine(); 9. 10. java.lang.arithmeticexception: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:8) Kizito (Makerere University) CSC 1214 March, 2018 8 / 24
try and catch Using try and catch 1. class Exc2 { 2. public static void main(string s[]) { 3. int d, a; 4. try { 5. d = 0; 6. a = 42 / d; 7. System.out.println("Unreachable"); 8. 9. catch(arithmeticexception e) { 10. System.out.println("Division by zero"); 11. // or display description of exception 12. // System.out.print( Exception: + e); 13. 14. System.out.println("After catch statement"); 15. 16. Output Division by zero. After catch statement. Kizito (Makerere University) CSC 1214 March, 2018 9 / 24
try and catch Using try and catch 1. class Exc2 { 2. public static void main(string s[]) { 3. int d, a; 4. try { 5. d = 0; 6. a = 42 / d; 7. System.out.println("Unreachable"); 8. 9. catch(arithmeticexception e) { 10. // System.out.println( Division by zero ); 11. // or display description of exception 12. System.out.print("Exception: " + e); 13. 14. System.out.println("After catch statement"); 15. 16. Output Exception: java.lang.arithmeticexception: / by zero After catch statement. Kizito (Makerere University) CSC 1214 March, 2018 10 / 24
try and catch Multiple catch clauses 1. class MultiCatch { 2. public static void main(string args[]) { 3. try { 4. int a = args.length; 5. System.out.println("a = " + a); 6. int b = 42 / a; 7. int c[] = {1; 8. c[42] = 99; 9. catch(arithmeticexception e) { 10. System.out.println("Divide by 0: " + e); 11. catch(arrayindexoutofboundsexception e) { 12. System.out.println("Array index oob: " + e); 13. 14. System.out.println("After try/catch blocks."); 15. 16. Output of command: java MultiCatch a = 0 Divide by 0: java.lang.arithmeticexception: / by zero After try/catch blocks. Output of command: java MultiCatch TestArg a = 1 Array index oob: java.lang.arrayindexoutofboundsexception After try/catch blocks. What if we don t know the type of Exception? Then have one catch for a generic exception: catch(exception e) All Exception objects are subclasses of Exception Kizito (Makerere University) CSC 1214 March, 2018 11 / 24
try and catch Multiple catch clauses 1. class MultiCatch { 2. public static void main(string args[]) { 3. try { 4. int a = args.length; 5. System.out.println("a = " + a); 6. int b = 42 / a; 7. int c[] = {1; 8. c[42] = 99; 9. catch(arithmeticexception e) { 10. System.out.println("Divide by 0: " + e); 11. catch(arrayindexoutofboundsexception e) { 12. System.out.println("Array index oob: " + e); 13. 14. System.out.println("After try/catch blocks."); 15. 16. Output of command: java MultiCatch a = 0 Divide by 0: java.lang.arithmeticexception: / by zero After try/catch blocks. Output of command: java MultiCatch TestArg a = 1 Array index oob: java.lang.arrayindexoutofboundsexception After try/catch blocks. What if we don t know the type of Exception? Then have one catch for a generic exception: catch(exception e) All Exception objects are subclasses of Exception Kizito (Makerere University) CSC 1214 March, 2018 11 / 24
try and catch Multiple catch clauses 1. class MultiCatch { 2. public static void main(string args[]) { 3. try { 4. int a = args.length; 5. System.out.println("a = " + a); 6. int b = 42 / a; 7. int c[] = {1; 8. c[42] = 99; 9. catch(arithmeticexception e) { 10. System.out.println("Divide by 0: " + e); 11. catch(arrayindexoutofboundsexception e) { 12. System.out.println("Array index oob: " + e); 13. 14. System.out.println("After try/catch blocks."); 15. 16. Output of command: java MultiCatch a = 0 Divide by 0: java.lang.arithmeticexception: / by zero After try/catch blocks. Output of command: java MultiCatch TestArg a = 1 Array index oob: java.lang.arrayindexoutofboundsexception After try/catch blocks. What if we don t know the type of Exception? Then have one catch for a generic exception: catch(exception e) All Exception objects are subclasses of Exception Kizito (Makerere University) CSC 1214 March, 2018 11 / 24
try and catch Nested try statements class NestTry { public static void main(string s[]) { try { //... try { // nested try block //... catch (ArrayIndexOutOfBoundsException e) { //... catch (ArithmeticException e) { //... Kizito (Makerere University) CSC 1214 March, 2018 12 / 24
try and catch Nested try via method calls class MethNestTry { static void nesttry(int a) { try { // nested try block //... catch(arrayindexoutofboundsexception e) { //... public static void main(string args[]) { try { int a = args.length; //... nesttry(a); //... catch(arithmeticexception e) { //... Kizito (Makerere University) CSC 1214 March, 2018 13 / 24
throw throw Previous examples catch exceptions that are thrown by the Java run-time system However, you can throw an exception explicitly General form: throw ThrowableInstance; ThrowableInstance must be an object of type Throwable or a subclass of Throwable The flow of execution stops immediately after the throw statement Kizito (Makerere University) CSC 1214 March, 2018 14 / 24
throw throw example 1 import java.util.scanner; public class DivideByZero { public static void main(string args[]) throws DivideByZeroException{ int numerator, denominator; Scanner scan = new Scanner(System.in); while(true) { System.out.print("Enter numerator:"); numerator = scan.nextint(); System.out.print("Enter denominator:"); denominator = scan.nextint(); if(denominator == 0) throw new DivideByZeroException("Zero Divisor"); System.out.println("Answer "+numerator/denominator); break; Kizito (Makerere University) CSC 1214 March, 2018 15 / 24
throw throw example 2 1. class ThrowDemo { 2. static void demoproc() { 3. try { 4. throw new NullPointerException("demo"); 5. catch(nullpointerexception e) { 6. System.out.println("Caught inside demoproc."); 7. throw e; // rethrow the exception 8. 9. 10. public static void main(string args[]) { 11. try { 12. demoproc(); 13. catch(nullpointerexception e) { 14. System.out.println("Recaught: " + e); 15. 16. 17. Output Caught inside demoproc. Recaught: java.lang.nullpointerexception: demo Kizito (Makerere University) CSC 1214 March, 2018 16 / 24
throws throws Syntax type method-name(parameter-list) throws exception-list { // body of method Example 1. class ThrowsDemo { 2. static void throwone() throws IllegalAccessException { 3. System.out.println("Inside throwone."); 4. throw new IllegalAccessException("demo"); 5. 6. 7. public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); 12. 13. 14. Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, 2018 17 / 24
throws throws Syntax type method-name(parameter-list) throws exception-list { // body of method Example 1. class ThrowsDemo { 2. static void throwone() throws IllegalAccessException { 3. System.out.println("Inside throwone."); 4. throw new IllegalAccessException("demo"); 5. 6. 7. public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); 12. 13. 14. Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, 2018 17 / 24
throws throws Syntax type method-name(parameter-list) throws exception-list { // body of method Example 1. class ThrowsDemo { 2. static void throwone() throws IllegalAccessException { 3. System.out.println("Inside throwone."); 4. throw new IllegalAccessException("demo"); 5. 6. 7. public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); 12. 13. 14. Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, 2018 17 / 24
finally finally finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block The finally block will execute whether or not the exception is thrown When a method is about to return to the caller from inside the try/catch block via an explicit return statement, the finally clause is also executed just before the method returns The finally clause is optional however, each try statement requires at least one catch or a finally clause Kizito (Makerere University) CSC 1214 March, 2018 18 / 24
finally finally example 1. class FinallyDemo { 2. // Through an exception out of the method 3. static void proca() { 4. try { 5. System.out.println("inside proca"); 6. throw new RuntimeException("demo"); 7. finally { 8. System.out.println("procA s finally"); 9. 10. 11. // Return from within a try block 12. static void procb() { 13. try { 14. System.out.println("inside procb"); 15. return; 16. finally { 17. System.out.println("procB s finally"); 18. 19. 20. // Execute a try block normally 21. static void procc() { 22. try { 23. System.out.println("inside procc"); 24. finally { 25. System.out.println("procC s finally"); 26. 27. 28. public static void main(string args[]) { 29. try { 30. proca(); 31. catch (Exception e) { 32. System.out.println("Exception caught"); 33. 34. procb(); 35. procc(); 36. 37. Output inside proca proca s finally Exception caught inside procb procb s finally inside procc procc s finally Kizito (Makerere University) CSC 1214 March, 2018 19 / 24
Defining Own Exceptions Defining Own Exceptions A programmer can define a custom exception by extending the Exception class or one of its descendants class DivideByZeroException extends Exception { // A constructor to initialise the exception object // with a particular message DivideByZeroException(String message) { super(message); Kizito (Makerere University) CSC 1214 March, 2018 20 / 24
Java s Exceptions Java s Built-in Exceptions ArithmeticException: Arithmetic error ArrayIndexOutOfBoundsException ArrayStoreException: Assignment to an array element of an incompatible type ClassCastException: Invalid cast IllegalArgumentException: Illegal argument used to invoke a method IllegalMonitorStateException: Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException: Environment or application is in incorrect state IllegalThreadStateException: Requested operation not compatible with current thread state IndexOutOfBoundsException: Some type of index is out-of-bounds NegativeArraySizeException: Array created with a negative size NullPointerException: Invalid use of null reference NumberFormatException: Invalid conversion of a string to a numeric format SecurityException: Attempt to violet security StringIndexOutOfBounds: Attempt to index outside the bounds of a string UnsupportedOperationException: An unsupported operation was encountered Kizito (Makerere University) CSC 1214 March, 2018 21 / 24
Java s Exceptions Java s Checked Exceptions need to be included in any method s throws list ClassNotFoundException CloneNotSupportedException: Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException: Access to a class is denied InstantiationException: Attempt to create an object of an abstract class or interface InterruptedException: One thread has been interrupted by another thread NoSuchFieldException NoSuchMethodException Kizito (Makerere University) CSC 1214 March, 2018 22 / 24
Java s Exceptions Checked Vs. Unchecked Exceptions An exception is either checked or unchecked A checked exception must either be caught or must 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 an error if a checked exception is not caught or listed in a throws clause An unchecked exception does not require explicit handling, though it could be processed nevertheless The only unchecked exceptions in Java are objects of type RuntimeException or any of its descendants Errors are similar to RuntimeException and its descendants Kizito (Makerere University) CSC 1214 March, 2018 23 / 24
Java s Exceptions The Exception Class Hierarchy Kizito (Makerere University) CSC 1214 March, 2018 24 / 24