CSC 1214: Object-Oriented Programming

Size: px
Start display at page:

Download "CSC 1214: Object-Oriented Programming"

Transcription

1 CSC 1214: Object-Oriented Programming J. Kizito Makerere University www: materials: e-learning environment: 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, / 24

2 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, / 24

3 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, / 24

4 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, / 24

5 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, / 24

6 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, / 24

7 Uncaught Exceptions Uncaught Exceptions 1. class Exc0 { 2. public static void main(string s[]) { 3. int d = 0; 4. int a = 42 / d; Output java.lang.arithmeticexception: at Exc0.main(Exc0.java:4) / by zero Kizito (Makerere University) CSC 1214 March, / 24

8 Uncaught Exceptions Output Uncaught Exceptions Error Reporting 1. class Exc1 { 2. static void subroutine() { 3. int d = 0; 4. int a = 10 / d; public static void main(string args[]) { 8. Exc1.subroutine(); java.lang.arithmeticexception: / by zero at Exc1.subroutine(Exc1.java:4) at Exc1.main(Exc1.java:8) Kizito (Makerere University) CSC 1214 March, / 24

9 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"); catch(arithmeticexception e) { 10. System.out.println("Division by zero"); 11. // or display description of exception 12. // System.out.print( Exception: + e); System.out.println("After catch statement"); Output Division by zero. After catch statement. Kizito (Makerere University) CSC 1214 March, / 24

10 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"); catch(arithmeticexception e) { 10. // System.out.println( Division by zero ); 11. // or display description of exception 12. System.out.print("Exception: " + e); System.out.println("After catch statement"); Output Exception: java.lang.arithmeticexception: / by zero After catch statement. Kizito (Makerere University) CSC 1214 March, / 24

11 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); System.out.println("After try/catch blocks."); 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, / 24

12 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); System.out.println("After try/catch blocks."); 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, / 24

13 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); System.out.println("After try/catch blocks."); 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, / 24

14 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, / 24

15 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, / 24

16 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, / 24

17 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, / 24

18 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 public static void main(string args[]) { 11. try { 12. demoproc(); 13. catch(nullpointerexception e) { 14. System.out.println("Recaught: " + e); Output Caught inside demoproc. Recaught: java.lang.nullpointerexception: demo Kizito (Makerere University) CSC 1214 March, / 24

19 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"); public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, / 24

20 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"); public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, / 24

21 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"); public static void main(string args[]) { 8. try { 9. throwone(); 10. catch (IllegalAccessException e) { 11. System.out.println("Caught " + e); Output Inside throwone. Caught java.lang.illegalaccessexception: demo Kizito (Makerere University) CSC 1214 March, / 24

22 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, / 24

23 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"); // 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"); // 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"); public static void main(string args[]) { 29. try { 30. proca(); 31. catch (Exception e) { 32. System.out.println("Exception caught"); procb(); 35. procc(); Output inside proca proca s finally Exception caught inside procb procb s finally inside procc procc s finally Kizito (Makerere University) CSC 1214 March, / 24

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, / 24

25 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, / 24

26 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, / 24

27 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, / 24

28 Java s Exceptions The Exception Class Hierarchy Kizito (Makerere University) CSC 1214 March, / 24

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

Unit 4. Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. Unit 4 Exception handling mechanism. new look try/catch mechanism in Java Enumeration in Java 5 - usage. exceptions An exception is an abnormal condition that arises in a code sequence at run time. an

More information

Unit III Exception Handling and I/O Exceptions-exception hierarchy-throwing and catching exceptions-built-in exceptions, creating own exceptions, Stack Trace Elements. Input /Output Basics-Streams-Byte

More information

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

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 Course Name: Advanced Java Lecture 5 Topics to be covered Exception Handling Exception HandlingHandlingIntroduction An exception is an abnormal condition that arises in a code sequence at run time A Java

More information

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

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1 Exceptions: An OO Way for Handling Errors Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such

More information

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

Here is a hierarchy of classes to deal with Input and Output streams. PART 15 15. Files and I/O 15.1 Reading and Writing Files A stream can be defined as a sequence of data. The InputStream is used to read data from a source and the OutputStream is used for writing data

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.2) Exception Handling 1 Outline Throw Throws Finally 2 Throw we have only been catching exceptions that are thrown by the Java run-time system. However, it

More information

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

Inheritance. Inheritance allows re-usability of the code. In Java, we use the terminology as super class and sub class. Inheritance Inheritance allows re-usability of the code. In Java, we use the terminology as super class and sub class. Inheritance is achieved using the keyword extends. Java does not support multiple

More information

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

UNIT - V. Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O UNIT - V Inheritance Interfaces and inner classes Exception handling Threads Streams and I/O 1 INHERITANCE 2 INHERITANCE What is Inheritance? Inheritance is the mechanism which allows a class B to inherit

More information

we dont take any liability for the notes correctness.

we dont take any liability for the notes correctness. 1 Unit 3 Topic:Multithreading and Exception Handling Unit 3/Lecture 1 MultiThreading [RGPV/June 2011(10)] Unlike many other computer languages, Java provides built-in support for multithreaded programming.

More information

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

Java Programming MCA 205 Unit - II. Learning Objectives. Introduction. 7/31/2013MCA-205 Java Programming Java Programming MCA 205 Unit - II UII. Learning Objectives Exception Handling: Fundamentals exception types, uncaught exceptions, throw, throw, final, built in exception, creating your own exceptions,

More information

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring Exceptions BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom

More information

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

Exception-Handling try catch throw throws finally try try catch throw throws finally Exception-Handling A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object representing

More information

BBM 102 Introduction to Programming II Spring 2017

BBM 102 Introduction to Programming II Spring 2017 BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception

More information

Unit 5 - Exception Handling & Multithreaded

Unit 5 - Exception Handling & Multithreaded Exceptions Handling An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception occurs the normal flow of the program is disrupted and the program/application

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Java lecture (10.1) Exception Handling 1 Outline Exception Handling Mechanisms Exception handling fundamentals Exception Types Uncaught exceptions Try and catch Multiple catch

More information

C16b: Exception Handling

C16b: Exception Handling CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions Overview Problem: Can we detect run-time errors and take corrective action? Try-catch Test for a variety of different program situations

More information

What are Exceptions?

What are Exceptions? Exception Handling What are Exceptions? The traditional approach Exception handing in Java Standard exceptions in Java Multiple catch handlers Catching multiple exceptions finally block Checked vs unchecked

More information

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

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception

More information

Chapter 12 Exception Handling

Chapter 12 Exception Handling Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can

More information

Exceptions Questions https://www.journaldev.com/2167/java-exception-interview-questionsand-answers https://www.baeldung.com/java-exceptions-interview-questions https://javaconceptoftheday.com/java-exception-handling-interviewquestions-and-answers/

More information

1 - Basics of Java. Explain features of JAVA.

1 - Basics of Java. Explain features of JAVA. 1 - Basics of Java Explain features of JAVA. Features of java is discussed below: Simple Java was designed to be easy for the professional programmer to learn and use effectively. Java is easy to master.

More information

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 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

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 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

Fundamentals of Object Oriented Programming

Fundamentals of Object Oriented Programming INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of

More information

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

Exception Handling in Java. An Exception is a compile time / runtime error that breaks off the Description Exception Handling in Java An Exception is a compile time / runtime error that breaks off the program s execution flow. These exceptions are accompanied with a system generated error message.

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions

More information

Java Programming Language Mr.Rungrote Phonkam

Java Programming Language Mr.Rungrote Phonkam 9 Java Programming Language Mr.Rungrote Phonkam rungrote@it.kmitl.ac.th Contents 1 Exception Handling 1.1. Implicitly Exception 1.2. Explicitly Exception 2. Handle Exception 3. Threads 1 Exception Handling

More information

Lecture 19 Programming Exceptions CSE11 Fall 2013

Lecture 19 Programming Exceptions CSE11 Fall 2013 Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:

More information

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

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors

More information

Introduction to Software Design

Introduction to Software Design CSI 1102 1 Abdulmotaleb El Saddik University of Ottawa School of Information Technology and Engineering (SITE) Multimedia Communications Research Laboratory (MCRLab) Distributed Collaborative Virtual Environments

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

File I/O and Exceptions

File I/O and Exceptions File I/O and Exceptions CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Some

More information

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 File I/O and Exceptions CSC 1051 Data Structures and Algorithms I I/O Streams Programs read information from input streams and write information to output streams Dr. Mary-Angela Papalaskari Department

More information

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

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Exceptions Chapter 10 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Exceptions: The purpose of exceptions Exception messages The call stack trace The try-catch statement Exception

More information

Data Structures. 02 Exception Handling

Data Structures. 02 Exception Handling David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.

More information

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSC207H: Software Design. Exceptions. CSC207 Winter 2018 Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,

More information

More on Exception Handling

More on Exception Handling Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

Object Oriented Programming Exception Handling

Object Oriented Programming Exception Handling Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of

More information

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COE318 Lecture Notes Week 10 (Nov 7, 2011) COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:

More information

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

2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don t have to throw, you can but isn t necessary EXCEPTIONS... 3 3 categories of exceptions:...3 1- Checked exception: thrown at the time of compilation....3 2- Runtime exception: UnChecked (execution of program) automatically propagated in java. don

More information

Exceptions: When something goes wrong. Image from Wikipedia

Exceptions: When something goes wrong. Image from Wikipedia Exceptions: When something goes wrong Image from Wikipedia Conditions that cause exceptions > Error internal to the Java Virtual Machine > Standard exceptions: Divide by zero Array index out of bounds

More information

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

exceptions catch (ArithmeticException exc) { // catch the exception System.out.println(Can't divide by Zero!); s // Subclasses must precede superclasses in catch statements. class ExcDemo5 { // Here, numer is longer than denom. int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 ; int denom[] = { 2, 0, 4, 4, 0, 8 ;

More information

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

Exception in thread main java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling. Exceptions 1 Handling exceptions A program will sometimes inadvertently ask the machine to do something which it cannot reasonably do, such as dividing by zero, or attempting to access a non-existent array

More information

Correctness and Robustness

Correctness and Robustness Correctness and Robustness 188230 Advanced Computer Programming Asst. Prof. Dr. Kanda Runapongsa Saikaew (krunapon@kku.ac.th) Department of Computer Engineering Khon Kaen University 1 Agenda Introduction

More information

Std 12 Lesson-10 Exception Handling in Java ( 1

Std 12 Lesson-10 Exception Handling in Java (  1 Ch-10 : Exception Handling in Java 1) It is usually understood that a compiled program is error free and will always successfully. (a) complete (b) execute (c) perform (d) accomplish 2) In few cases a

More information

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

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11 Administration Exceptions CS 99 Summer 2000 Michael Clarkson Lecture 11 Lab 10 due tomorrow No lab tomorrow Work on final projects Remaining office hours Rick: today 2-3 Michael: Thursday 10-noon, Monday

More information

Chapter 13 Exception Handling

Chapter 13 Exception Handling Chapter 13 Exception Handling 1 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can continue to run or

More information

Download link: Java Exception Handling

Download link:  Java Exception Handling What is an Exception? Java Exception Handling Error that occurs during runtime Exceptional event Cause normal program flow to be disrupted Java Exception Examples 1. Divide by zero errors 2. Accessing

More information

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

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception

More information

Exceptions. CSC207 Winter 2017

Exceptions. CSC207 Winter 2017 Exceptions CSC207 Winter 2017 What are exceptions? In Java, an exception is an object. Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment:

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the mean, or -1 if the array has length 0. 3 ***************************************************

More information

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

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception

More information

Unit III Rupali Sherekar 2017

Unit III Rupali Sherekar 2017 Unit III Exceptions An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. In computer languages that do not support exception

More information

Exception Handling in Java

Exception Handling in Java Exception Handling in Java The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

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

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture. (part 2) December 3, 2007 Quick Review of Last Lecture ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor: Alexander Stoytchev An exception is an object that describes an unusual

More information

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

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions

More information

Full file at Chapter 2 - Inheritance and Exception Handling

Full file at   Chapter 2 - Inheritance and Exception Handling Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a

More information

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

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed 1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.

More information

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

For more details on SUN Certifications, visit

For more details on SUN Certifications, visit Exception Handling For more details on SUN Certifications, visit http://sunjavasnips.blogspot.com/ Q: 01 Given: 11. public static void parse(string str) { 12. try { 13. float f = Float.parseFloat(str);

More information

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

National University. Faculty of Computer Since and Technology Object Oriented Programming National University Faculty of Computer Since and Technology Object Oriented Programming Lec (8) Exceptions in Java Exceptions in Java What is an exception? An exception is an error condition that changes

More information

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

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes

More information

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

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others COMP-202 Exceptions Lecture Outline Exceptions Exception Handling The try-catch statement The try-catch-finally statement Exception propagation Checked Exceptions 2 Exceptions An exception is an object

More information

Exception handling in Java. J. Pöial

Exception handling in Java. J. Pöial Exception handling in Java J. Pöial Errors and exceptions Error handling without dedicated tools: return codes, global error states etc. Problem: it is not reasonable (or even possible) to handle each

More information

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

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 7 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential

More information

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

Exceptions. What exceptional things might our programs run in to? Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don

More information

CSCI 261 Computer Science II

CSCI 261 Computer Science II CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -

More information

Exception-Handling Overview

Exception-Handling Overview م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the

More information

CS 3 Introduction to Software Engineering. 3: Exceptions

CS 3 Introduction to Software Engineering. 3: Exceptions CS 3 Introduction to Software Engineering 3: Exceptions Questions? 2 Objectives Last Time: Procedural Abstraction This Time: Procedural Abstraction II Focus on Exceptions. Starting Next Time: Data Abstraction

More information

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

Exceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

Introductory Programming Exceptions and I/O: sections

Introductory Programming Exceptions and I/O: sections Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate

More information

17. Handling Runtime Problems

17. Handling Runtime Problems Handling Runtime Problems 17.1 17. Handling Runtime Problems What are exceptions? Using the try structure Creating your own exceptions Methods that throw exceptions SKILLBUILDERS Handling Runtime Problems

More information

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

IS311 Programming Concepts 2/59. AVA Exception Handling Jการจ ดการส งผ ดปรกต 1 IS311 Programming Concepts 2/59 AVA Exception Handling Jการจ ดการส งผ ดปรกต 2 Introduction Users have high expectations for the code we produce. Users will use our programs in unexpected ways. Due to

More information

Recitation 3. 2D Arrays, Exceptions

Recitation 3. 2D Arrays, Exceptions Recitation 3 2D Arrays, Exceptions 2D arrays 2D Arrays Many applications have multidimensional structures: Matrix operations Collection of lists Board games (Chess, Checkers) Images (rows and columns of

More information

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

COSC 123 Computer Creativity. I/O Streams and Exceptions. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity I/O Streams and Exceptions Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Objectives Explain the purpose of exceptions. Examine the try-catch-finally

More information

Chapter 14. Exception Handling and Event Handling ISBN

Chapter 14. Exception Handling and Event Handling ISBN Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction

More information

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

EXCEPTION HANDLING. // code that may throw an exception } catch (ExceptionType parametername) { EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could

More information

Errors and Exceptions

Errors and Exceptions Exceptions Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null reference An exception isn t necessarily your fault trying

More information

Exceptions - Example. Exceptions - Example

Exceptions - Example. Exceptions - Example - Example //precondition: x >= 0 public void sqrt(double x) double root; if (x < 0.0) //What to do? else //compute the square root of x return root; 1 - Example //precondition: x >= 0 public void sqrt(double

More information

Exception Handling. Exception Handling

Exception Handling. Exception Handling References: Jacquie Barker, Beginning Java Objects ; Rick Mercer, Computing Fundamentals With Java; Wirfs - Brock et. al., Martin Fowler, OOPSLA 99 Tutorial ; internet notes; notes:h. Conrad Cunningham

More information

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

Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws Lecture 14 Summary Exceptions vs. Errors Exceptions vs. RuntimeExceptions try...catch...finally throw and throws 1 By the end of this lecture, you will be able to differentiate between errors, exceptions,

More information

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

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming Chapter 10 Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2

More information

CSE 143 Java. Exceptions 1/25/

CSE 143 Java. Exceptions 1/25/ CSE 143 Java Exceptions 1/25/17 12-1 Verifying Validity of Input Parameters A non-private method should always perform parameter validation as its caller is out of scope of its implementation http://docs.oracle.com/javase/7/docs/technotes/guides/language/assert.html

More information

Software Practice 1 - Error Handling

Software Practice 1 - Error Handling Software Practice 1 - Error Handling Exception Exception Hierarchy Catching Exception Userdefined Exception Practice#5 Prof. Joonwon Lee T.A. Jaehyun Song Jongseok Kim (42) T.A. Sujin Oh Junseong Lee 1

More information

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

EXCEPTIONS. Objectives. The try and catch Statements. Define exceptions. Use try, catch and finally statements. Describe exception categories Objectives Define exceptions 8 EXCEPTIONS Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions 271 272 Exceptions

More information

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

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED 엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance

More information

CS159. Nathan Sprague

CS159. Nathan Sprague CS159 Nathan Sprague What s wrong with the following code? 1 /* ************************************************** 2 * Return the maximum, or Integer. MIN_VALUE 3 * if the array has length 0. 4 ***************************************************

More information

EXCEPTION HANDLING. Summer 2018

EXCEPTION HANDLING. Summer 2018 EXCEPTION HANDLING Summer 2018 EXCEPTIONS An exception is an object that represents an error or exceptional event that has occurred. These events are usually errors that occur because the run-time environment

More information

Exceptions Handling Errors using Exceptions

Exceptions Handling Errors using Exceptions Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java

More information

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

1. Find the output of following java program. class MainClass { public static void main (String arg[]) 1. Find the output of following java program. public static void main(string arg[]) int arr[][]=4,3,2,1; int i,j; for(i=1;i>-1;i--) for(j=1;j>-1;j--) System.out.print(arr[i][j]); 1234 The above java program

More information

EXCEPTIONS. Java Programming

EXCEPTIONS. Java Programming 8 EXCEPTIONS 271 Objectives Define exceptions Exceptions 8 Use try, catch and finally statements Describe exception categories Identify common exceptions Develop programs to handle your own exceptions

More information

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Chapter 11 Handling Exceptions and Events. Chapter Objectives Chapter 11 Handling Exceptions and Events Chapter Objectives Learn what an exception is See how a try/catch block is used to handle exceptions Become aware of the hierarchy of exception classes Learn about

More information

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

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited Chapter 12 Exception Handling and Text IO Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited 2015 1 Motivations When a program runs into a runtime error,

More information

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

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions COMP 213 Advanced Object-oriented Programming Lecture 17 Exceptions Errors Writing programs is not trivial. Most (large) programs that are written contain errors: in some way, the program doesn t do what

More information

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

EXCEPTION-HANDLING INTRIVIEW QUESTIONS EXCEPTION-HANDLING INTRIVIEW QUESTIONS Q1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is

More information

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

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166 Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions

More information