Programming II (CS300)

Size: px
Start display at page:

Download "Programming II (CS300)"

Transcription

1 1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM Fall 2018

2 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and Annotations Keep in Mind

3 Introduction (Correctness vs Robustness) 3 A program is Correct: if it returns the desired output given any set of input data A Correct program accomplishes the task that it was designed to perform Robust: if it can survive unusual or exceptional circumstances without crashing

4 Introduction (What is an exception?) 4 Exception An exceptional event, which occurs during the execution of a program, that interrupts the normal execution flow of the program An exception may be a runtime error, a not handled special case.

5 Introduction (What is an exception?) 5 Exception (Examples) A program will crash (the program execution terminates abnormally) if it tries to use an array element A[i] when the index i is out of the range of indices declared for the array A. (use of a bad index) read a bad input data provided by the user (for example, the program expects from the user to enter an integer. But, the user provides a float, or a char, or a String, instead, as input). open a non-existing file etc.

6 Introduction 6 Exception (Example) import java.util.*; public class ArrayException { private final static int classcapacity = 10; private final static int studentcount = 12; private static int[] scores = new int[classcapacity]; private static Student[] students = new Student[studentCount]; public static void main(string[] args) { // creating and adding (enrolling) students for(int i = 0; i < studentcount; i++) { students[i] = new Student(); } } } // Adding random scores between 0 and 100% Random randgen = new Random(100); for(int i = 0; i<studentcount; i++ ) { scores[i] = randgen.nextint(); }

7 Introduction 7 How to make our program robust?

8 Introduction (How to deal with exceptions?) 8 Practice Examples #1: Use of if see ArrayException.java (version 1.0 and version 2.0) Question? In the general case, is it recommended to use if else statements to handle exceptions?

9 Introduction (How to deal with exceptions?) 9 Problems with use of if statement to handle exceptions It is difficult and sometimes impossible to anticipate all the possible things that might go wrong. It s not always clear what to do when an error is detected. Affect the clarity of a program Trying to anticipate all the possible problems can turn what would otherwise be a straightforward program into a messy tangle of if statements

10 Exception Handling 10 Exception handling A technique for dealing with exceptions that can occur while a program is running In Java, exception handling codes are separated from the main logic via the try-catch-finally construct

11 Exception Handling 11 Try bloc A try block encloses code that might generate an exception Catch bloc A catch block processes an exception

12 Exceptions in Java: Class Hierarchy 12 Throwable class (java.lang.throwable) is the base class for all Exception classes

13 Exceptions in Java: Throwable class 13 Throwable class and its sub-classes All exception objects belong to a subclass of the standard class java.lang.throwable The previous diagram shows how the different classes and subclasses of exceptions and errors are arranged This diagram is called class hierarchy. It shows the relationship among various types of exception

14 Exceptions in Java: class Exception 14 Exception class in Java Throwable has two direct subclasses, Error and Exception. Each one of them in turn has many other predefined subclasses. Subclasses of the class Exception represent exceptions that can be caught A RuntimeException generally indicates a bug in the program, that the programmer should fix rather than handle it with a trycatch block Exception subclasses that require mandatory exception-handling are shown in green in the above diagram. They represent checked exceptions The programmer can create new exception subclasses to represent new types of exception

15 Exception Handling 15 Some objects that are created in a try block must be cleaned up For instance, files that are opened in the try block may need to be closed prior to leaving the try block. Finally clause follows a try block or a catch block consists of the keyword finally followed by the finally block

16 Exception Handling 16 try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block } finally { // The finally block always executes. }

17 Exception Handling 17 Finally clause (Basic Scenarios) 1. If the try block executes without exception control passes to the finally block. 2. If an uncaught exception is encountered inside the try block, control passes to the finally block, After executing the finally block, the exception propagates. 3. If a caught exception is encountered in the try block, control passes to the appropriate catch block, After executing the catch block, the finally block is executed.

18 Common Exceptions 18 Types of exceptions Checked exceptions Checked exceptions are checked at compile-time The compiler checks them during compilation If these exceptions are not handled/declared in the program, the compiler returns a compilation error All exceptions other than Runtime Exceptions are known as Checked exceptions Unchecked exceptions Unchecked exceptions are not checked at compile-time It s the responsibility of the programmer to handle these exceptions

19 Common Exceptions 19

20 Common Exceptions 20 Standard Runtime Exceptions ArithmeticException NumberFormatException IndexOutOfBoundsException NegativeArraySizeException NullPointerException NoSuchElementException Meaning Overflow or integer division by zero Illegal conversion of String to numeric type Illegal index into an array or String Attempt to create a negative-length array Illegal attempt to use a null reference Failed attempt to obtain next item

21 Common Exceptions 21 Standard Checked Exceptions java.io.eofexception java.io.filenotfoundexception java.io.ioexception InterruptedException Meaning End-of-file before completion of input File not found to open Includes most I/O exceptions Thrown by the Thread.sleep method

22 Throwing Exceptions 22 The keyword throw is used to throw a new Exception Syntax of throw statement throw <exception-object>; <exception-object> should be an object belonging to one of the subclasses of the Exception class Example throw new ArithmeticException("Division by zero"); This is the error message in the exception object A program can throw an exception hoping that some part of the program would catch and handle that exception

23 Throwing Exceptions with Methods 23 Declaring an Exception Declare the exception in the signature of the method using throws keyword. Example public void realrootsolver() throws IllegalArgumentException Handling an Exception Handle the exceptions using try-catch-finally blocks If a method declares an exception using throws keyword, this exception should be explicitly handled when calling/using that method. It is a good practice to handle all exceptions declared using throws keyword

24 Throwing Exceptions with Methods 24 Be carrefull! throws is different from throw throws is used to declare a method that may throw two exceptions named AbcException and EfgException. These two exceptions should be explicitly handled (as checked exceptions). public void methoda() throws AbcException, EfgException { // method s signature // method s body } // AbcException occurs if (...) throw new AbcException(...); // construct an AbcException object and throw it to JVM... // EfgException occurs if (...) throw new EfgException(...); // construct an EfgException object and throw it to JVM... throw is generally followed by the keyword new and is used to create a new Exception type object and throw it.

25 Throwing Exceptions with Methods 25 Catching a declared exception To use the methoda defined in the previous slide in another method (for instance methodb), two options are possible: 1. Wrap the call of methoda() inside a try-catch (or try-catch-finally) 2. Suppose that methodb() who calls methoda() does not wish to handle the exceptions (via a try-catch). In this case, these exceptions should be thrown up the call stack in methodb s signature using the keyword throws

26 Throwing Exceptions with Methods public void methoda() throws AbcException, EfgException{... } public void methodb(){ // no exception declared }... Try{ // uses methoda() that declares AbcException and EfgException methoda();... } catch(abcexception e1){ // Exception handler for AbcExcpetion... } catch(efgexception e2){ // Exception handler for EfgExcpetion... } finally{ // optional (always runs)) // These lines of code always run, used generally for cleaning up... }... Option 1 Option 2 26 Public void methodb() throws AbcException, EfgException { // pass the exception object for the next level... // method to handle // uses methoda() which declares throws AbcException, EfgException methoda(); // no need for try-catch here as methodb() declares the two exceptions in its signature... }

27 Exception Handling 27 Practice Example 1 (Sequential files: File I/O) Three steps of File I/O 1. Open/create a file 2. Read/Write/do something with the file 3. Close the file We will be using the following classes of File I/O in Java 1. File: import java.io.file; 2. PrintWriter: import java.io.printwriter; or PrintStream: import java.io.printstream; 3. Scanner: import java.util.scanner;

28 Exception Handling 28 Practice Example 1 (Sequential files) Steps to use a Scanner to perform File I/O 1. Create a file object using a given filename 2. Create a Scanner object using the File object 3. Read data from file and process the data 4. Close the file using close method Exception handling is necessary when performing a file I/O Incorrect file name, error while opening the file, etc.

29 Exception Handling 29 Practice Example 1 (Sequential files) Use of Final Clause The reference to the Scanner must be declared outside of the try block in order to be visible in the finally block. The reference to the Scanner must be initialized to null to avoid compiler complaints about a possible uninitialized variable. Prior to calling close, check that the reference to the Scanner is not null to avoid generating a NullPointerException

30 Practice Example #2 30 Read from a file using Scanner and File Student.java and ReadStudentNames.java

31 Practice Example #3 31 Write in a file using File and PrintStream Student.java and ReadWriteStudentNames.java

32 Practice Example #4 32 Throwing see QuadraticEquation.java

33 Try-with-resources statement (Optional) The try-with-resources statement is a try statement that declares one or more resources A resource is an object that will be automatically closed at the end of the execution of the try-catch-finally block The resource must be represented by an object that implements the AutoCloseable interface. This interface defines a single method named close(). The try-with-resources statement ensures that each resource is closed at the end of the statement. A resource object is local to the try bloc Syntax try(<resource objects>){ }catch( ){ }finally{ } 33

34 Try-with-resources statement (Optional) 34 Practice Example TryStatementDemo.java

35 Assertions and Annotations (optional) 35 Assertions Precondition A condition that must be true just before the execution of some section of the code. So, the program can continue running correctly from that point. Post-condition A condition that is true at a certain point in the program as a consequence of the code that has been executed before that point. Assertion Statement in Java assert < condition > ; assert < condition > : < error-message >;

36 Assertions 36 The statement assert < condition >; // or assert < condition > : < error-message >; is similar to if ( <condition> == false ) throw new AssertionError( <error-message>); To be used, assertions should be enabled in Java

37 Assertions (optional) 37 Question: when to use assertions instead of exceptions? Answer: Assertions are generally used to test your program (to test conditions that should definitely be true if your program is correct. It helps also debugging your program. Be careful! Assertions do not represent an alternative to handle Exceptions. You can use an assertion instead of an exception handling bloc if you are sure that your program will never throw that exception while running.

38 Assertions (optional) 38 Example of use of Practice Example #4 realrootsolverbis() method related to QuadraticEquation.java

39 Assertions versus Exceptions (optional) 39 Assertions Exceptions Assertions should not be used for checking if a user violates the contact of public methods (for instance passing illegal parameters) Assertions are generally used to help in testing or debugging a code If a user passes illegal parameters to a method, an exception should be thrown Exceptions are generally used to alert the users of a misuse of your code

40 Annotations (optional) 40 Annotations Notes added to a main text to help you understand it Kind of metadata added to a program Comments on a program are a kind of annotations Comments are ignored by the compiler and have no effect on the running flow of a program Java doc comments are processed by a specific program (not the compiler) and used to create API documentation

41 Annotations (optional) 41 Examples of Standard Annotations (other than a standard annotation commonly used to annotate method definitions. It means that the method is intended to override (that is replace) a method with the same signature that was defined in some superclass. public void tostring() {... } If there is no "tostring()" method in any superclass, then the compiler can issue an annotation can help the programmer writing correct programs. The programmer can be warned about a potential error (overriding a method does not already defined in any superclass) at compile-time

42 Annotations (optional) 42 Examples of Standard Annotations (other than used to mark deprecated classes, methods, and variables. (A deprecated item is one that is considered to be obsolete, but is still part of the Java language for backwards compatibility for old <item> allows a compiler to generate warnings when the deprecated item is used

43 Annotations of Warning to be suppressed>) When used, a compiler will turn off warning messages that would ordinarily be generated when a class or method is compiled. no warnings about the use of deprecated items will be emitted when the class or method is compiled.

44 Keep in Mind 44 A try block encloses code that might generate an exception. A catch block processes an exception. Checked exceptions must be handled using try-catch-finally blocs or listed in a throws clause Unchecked exceptions do not have to be handled The finally bloc gets always executed regardless if an exception is thrown or processed A try-catch-finally bloc may contain several catch blocs The throw clause or keyword is used to throw an exception The throws clause or keyword indicates propagated exceptions

45 Keep in Mind 45 Make sure to clean up resources in the finally bloc (such as Input/Output Streams) or use try-with-resource statement It is a good practice to declare the specific exceptions that may occur in your method and should be checked using the keyword throws This promotes the re-usability of your code The caller of your method will be able to handle the exception better or avoid it with an additional check. To promote the clarity of your code, make sure to add declaration to your method comment and to describe the situations that can cause the exception

46 Keep in Mind 46 Catch the most specific exception first Eclipse reports an unreachable code block when you try to catch the less specific exception first. Refer to the Exceptions class diagram to figure out what exception are more specific than others Sub-classes are more specific than super-classes Only the first catch block that matches the exception gets executed For example, if you catch a RuntimeException first, you will never reach the catch block that should handle the more specific ArithmeticException because it s a subclass of the RuntimeException superclass.

47 Keep in mind 47 Java Exceptions Hierarchy Diagram

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

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

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

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

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

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

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

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

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

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

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

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

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

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 8 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments Assignment 4 is out and due on Tuesday Bugs and Exception handling 2 Bugs... often use the word bug when there

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

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. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology Exceptions Algorithms Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie Exceptions ± Definition

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

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

6.Introducing Classes 9. Exceptions

6.Introducing Classes 9. Exceptions 6.Introducing Classes 9. Exceptions Sisoft Technologies Pvt Ltd SRC E7, Shipra Riviera Bazar, Gyan Khand-3, Indirapuram, Ghaziabad Website: www.sisoft.in Email:info@sisoft.in Phone: +91-9999-283-283 Learning

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

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

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

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

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

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

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

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

CS112 Lecture: Exceptions and Assertions

CS112 Lecture: Exceptions and Assertions Objectives: CS112 Lecture: Exceptions and Assertions 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions 3. Introduce assertions Materials: 1. Online Java documentation

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

16-Dec-10. Consider the following method:

16-Dec-10. Consider the following method: Boaz Kantor Introduction to Computer Science IDC Herzliya Exception is a class. Java comes with many, we can write our own. The Exception objects, along with some Java-specific structures, allow us to

More information

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions

Exceptions. Errors and Exceptions. Dealing with exceptions. What to do about errors and exceptions Errors and Exceptions 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 is a problem whose cause is outside

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

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

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar

Exceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

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

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

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

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming 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:

More information

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions CS112 Lecture: Exceptions Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions Materials: 1. Online Java documentation to project 2. ExceptionDemo.java to

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

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

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

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/

More information

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions.

Pages and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines for more effective use of exceptions. CS511, HANDOUT 12, 7 February 2007 Exceptions READING: Chapter 4 in [PDJ] rationale for exceptions in general. Pages 56-63 and 68 in [JN] conventions for using exceptions in Java. Chapter 8 in [EJ] guidelines

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

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations

Topic 6: Exceptions. Exceptions are a Java mechanism for dealing with errors & unusual situations Topic 6: Exceptions Exceptions are a Java mechanism for dealing with errors & unusual situations Goals: learn how to... think about different responses to errors write code that catches exceptions write

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

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

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

Exceptions. Examples of code which shows the syntax and all that

Exceptions. Examples of code which shows the syntax and all that Exceptions Examples of code which shows the syntax and all that When a method might cause a checked exception So the main difference between checked and unchecked exceptions was that the compiler forces

More information

Motivations. Chapter 12 Exceptions and File Input/Output

Motivations. Chapter 12 Exceptions and File Input/Output Chapter 12 Exceptions and File Input/Output CS1: Java Programming Colorado State University Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the

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

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing Exceptions Chapter 15 Exception Handling Chapter Goals To learn how to throw exceptions To be able to design your own exception classes To understand the difference between checked and unchecked exceptions To learn

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. CSE 142, Summer 2002 Computer Programming 1. Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»

More information

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1. Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented

More information

Internal Classes and Exceptions

Internal Classes and Exceptions Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today

More information

Program Correctness and Efficiency. Chapter 2

Program Correctness and Efficiency. Chapter 2 Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you

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

Java Loose Ends. 11 December 2017 OSU CSE 1

Java Loose Ends. 11 December 2017 OSU CSE 1 Java Loose Ends 11 December 2017 OSU CSE 1 What Else? A few Java issues introduced earlier deserve a more in-depth treatment: Try-Catch and Exceptions Members (static vs. instance) Nested interfaces and

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

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO CS 112 Programming 2 Lecture 08 Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO rights reserved. 2 Motivation When a program runs into a runtime error, the program terminates

More information

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked exceptions Java try statement Final wishes Java try-resource

More information

Sri Vidya College of Engineering & Technology Question Bank

Sri Vidya College of Engineering & Technology Question Bank 1. What is exception? UNIT III EXCEPTION HANDLING AND I/O Part A Question Bank An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program s instructions.

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

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

ASSERTIONS AND LOGGING

ASSERTIONS AND LOGGING SUMMARY Exception handling, ASSERTIONS AND LOGGING PROGRAMMAZIONE CONCORRENTE E DISTR. Università degli Studi di Padova Dipartimento di Matematica Corso di Laurea in Informatica, A.A. 2015 2016 rcardin@math.unipd.it

More information

Exceptions and Error Handling

Exceptions and Error Handling Exceptions and Error Handling Michael Brockway January 16, 2015 Some causes of failures Incorrect implementation does not meet the specification. Inappropriate object request invalid index. Inconsistent

More information

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES 1 2 13 Exception Handling It is common sense to take a method and try it. If it fails, admit it frankly and try another. But above all, try something. Franklin Delano Roosevelt O throw away the worser

More information

Introduction Unit 4: Input, output and exceptions

Introduction Unit 4: Input, output and exceptions Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Introduction Unit 4: Input, output and exceptions 1 1.

More information

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun

CS 61B Data Structures and Programming Methodology. July 7, 2008 David Sun CS 61B Data Structures and Programming Methodology July 7, 2008 David Sun Announcements You ve started (or finished) project 1, right? Package Visibility public declarations represent specifications what

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

Introduction to Computer Science II CS S-22 Exceptions

Introduction to Computer Science II CS S-22 Exceptions Introduction to Computer Science II CS112-2012S-22 Exceptions David Galles Department of Computer Science University of San Francisco 22-0: Errors Errors can occur in program Invalid input / bad data Unexpected

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

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved. Chapter 9 Exception Handling Copyright 2016 Pearson Inc. All rights reserved. Last modified 2015-10-02 by C Hoang 9-2 Introduction to Exception Handling Sometimes the best outcome can be when nothing unusual

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

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

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1 CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship Java Review - Errors George Blankenship 1 Errors Exceptions Debugging Java Review Topics Java Review - Errors George Blankenship

More information

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship CSCI 6234 Object Oriented Design: Java Review Errors George Blankenship George Blankenship 1 Errors Exceptions Debugging Java Review Topics George Blankenship 2 Program Errors Types of errors Compile-time

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

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions A problem?... Exceptions Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions 2 A problem?... A problem?... 3 4 A problem?... A problem?... 5 6 A problem?...

More information

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program

More information

Typecasts and Dynamic Dispatch. Dynamic dispatch

Typecasts and Dynamic Dispatch. Dynamic dispatch Typecasts and Dynamic Dispatch Abstract Data Type (ADT) Abstraction Program Robustness Exceptions D0010E Lecture 8 Template Design Pattern Review: I/O Typecasts change the type of expressions as interpreted

More information

CS 251 Intermediate Programming Exceptions

CS 251 Intermediate Programming Exceptions CS 251 Intermediate Programming Exceptions Brooke Chenoweth University of New Mexico Fall 2018 Expecting the Unexpected Most of the time our programs behave well, however sometimes unexpected things happen.

More information

Defensive Programming. Ric Glassey

Defensive Programming. Ric Glassey Defensive Programming Ric Glassey glassey@kth.se Outline Defensive Programming Aim: Develop the programming skills to anticipate problems beyond control that may occur at runtime Responsibility Exception

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

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations.

09/08/2017 CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. CS2530 INTERMEDIATE COMPUTING 9/8/2017 FALL 2017 MICHAEL J. HOLMES UNIVERSITY OF NORTHERN IOWA TODAY S TOPIC: Exceptions and enumerations. 1 RUNTIME ERRORS All of us have experienced syntax errors. This

More information

Assertions and Exceptions Lecture 11 Fall 2005

Assertions and Exceptions Lecture 11 Fall 2005 Assertions and Exceptions 6.170 Lecture 11 Fall 2005 10.1. Introduction In this lecture, we ll look at Java s exception mechanism. As always, we ll focus more on design issues than the details of the language,

More information

Exceptions and Libraries

Exceptions and Libraries Exceptions and Libraries RS 9.3, 6.4 Some slides created by Marty Stepp http://www.cs.washington.edu/143/ Edited by Sarah Heckman 1 Exceptions exception: An object representing an error or unusual condition.

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

CS 209 Programming in Java #10 Exception Handling

CS 209 Programming in Java #10 Exception Handling CS 209 Programming in Java #10 Exception Handling Textbook Chapter 15 Spring, 2006 Instructor: J.G. Neal 1 Topics What is an Exception? Exception Handling Fundamentals Errors and Exceptions The try-catch-finally

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

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