CSC 1214: Object-Oriented Programming

Similar documents
Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage.


Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

Here is a hierarchy of classes to deal with Input and Output streams.

Object Oriented Programming

Inheritance. Inheritance allows re-usability of the code. In Java, we use the terminology as super class and sub class.

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O

we dont take any liability for the notes correctness.

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming

BBM 102 Introduction to Programming II Spring Exceptions

Exception-Handling try catch throw throws finally try try catch throw throws finally

BBM 102 Introduction to Programming II Spring 2017

Unit 5 - Exception Handling & Multithreaded

Object Oriented Programming

C16b: Exception Handling

Programming II (CS300)

ECE 122. Engineering Problem Solving with Java

What are Exceptions?

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Chapter 12 Exception Handling


1 - Basics of Java. Explain features of JAVA.

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Fundamentals of Object Oriented Programming

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the

Programming II (CS300)

Java Programming Language Mr.Rungrote Phonkam

Lecture 19 Programming Exceptions CSE11 Fall 2013

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

Introduction to Software Design

More on Exception Handling

File I/O and Exceptions

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Data Structures. 02 Exception Handling

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

More on Exception Handling

Object Oriented Programming Exception Handling

COE318 Lecture Notes Week 10 (Nov 7, 2011)

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary

Exceptions: When something goes wrong. Image from Wikipedia

exceptions catch (ArithmeticException exc) { // catch the exception System.out.println("Can't divide by Zero!");

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Correctness and Robustness

Std 12 Lesson-10 Exception Handling in Java ( 1

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Chapter 13 Exception Handling

Download link: Java Exception Handling

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Exceptions. CSC207 Winter 2017

CS159. Nathan Sprague

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Unit III Rupali Sherekar 2017

Exception Handling in Java

ITI Introduction to Computing II

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

ITI Introduction to Computing II

Full file at Chapter 2 - Inheritance and Exception Handling

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

For more details on SUN Certifications, visit

National University. Faculty of Computer Since and Technology Object Oriented Programming

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

Exception handling in Java. J. Pöial

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Exceptions. What exceptional things might our programs run in to?

CSCI 261 Computer Science II

Exception-Handling Overview

CS 3 Introduction to Software Engineering. 3: Exceptions

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions

Introductory Programming Exceptions and I/O: sections

17. Handling Runtime Problems

IS311 Programming Concepts 2/59. AVA Exception Handling Jการจ ดการส งผ ดปรกต

Recitation 3. 2D Arrays, Exceptions

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan

Chapter 14. Exception Handling and Event Handling ISBN

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) {

Errors and Exceptions

Exceptions - Example. Exceptions - Example

Exception Handling. Exception Handling

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

CSE 143 Java. Exceptions 1/25/

Software Practice 1 - Error Handling

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

CS159. Nathan Sprague

EXCEPTION HANDLING. Summer 2018

Exceptions Handling Errors using Exceptions

1. Find the output of following java program. class MainClass { public static void main (String arg[])

EXCEPTIONS. Java Programming

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Transcription:

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