Programming II (CS300)

Similar documents
Programming II (CS300)

Exception-Handling Overview

BBM 102 Introduction to Programming II Spring Exceptions

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

Object Oriented Programming

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Exception Handling. 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:

Exceptions. CSC207 Winter 2017

ECE 122. Engineering Problem Solving with Java

CS159. Nathan Sprague

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

BBM 102 Introduction to Programming II Spring 2017

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

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

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Chapter 12 Exception Handling

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

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

CS159. Nathan Sprague

Data Structures. 02 Exception Handling

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

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

Exceptions. Produced by. Algorithms. Eamonn de Leastar Department of Computing, Maths & Physics Waterford Institute of Technology

CS112 Lecture: Exceptions and Assertions

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

ITI Introduction to Computing II

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

Errors and Exceptions

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

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

EXCEPTION HANDLING. Summer 2018

CSCI 261 Computer Science II

ITI Introduction to Computing II

16-Dec-10. Consider the following method:

What are Exceptions?

More on Exception Handling

More on Exception Handling

Object Oriented Programming Exception Handling

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

Correctness and Robustness

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

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

Chapter 13 Exception Handling

Lecture 19 Programming Exceptions CSE11 Fall 2013

Motivations. Chapter 12 Exceptions and File Input/Output

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

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

CSC 1214: Object-Oriented Programming

Exceptions and Error Handling

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

Internal Classes and Exceptions

6.Introducing Classes 9. Exceptions

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

Java Loose Ends. 11 December 2017 OSU CSE 1

C16b: Exception Handling

Fundamentals of Object Oriented Programming

ASSERTIONS AND LOGGING

Chapter 14. Exception Handling and Event Handling ISBN

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

Introduction Unit 4: Input, output and exceptions

Program Correctness and Efficiency. Chapter 2

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

Introduction to Computer Science II CS S-22 Exceptions

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

Exceptions - Example. Exceptions - Example

Sri Vidya College of Engineering & Technology Question Bank

Exceptions Handling Errors using Exceptions

Typecasts and Dynamic Dispatch. Dynamic dispatch

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

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

Std 12 Lesson-10 Exception Handling in Java ( 1

Exception Handling in Java

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

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

CS 209 Programming in Java #10 Exception Handling

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

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

Introductory Programming Exceptions and I/O: sections

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

CS 251 Intermediate Programming Exceptions

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

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Defensive Programming. Ric Glassey

Assertions and Exceptions Lecture 11 Fall 2005

CS 231 Data Structures and Algorithms, Fall 2016

Exceptions and Libraries

17. Handling Runtime Problems

JAC444 - Lecture 4. Segment 1 - Exception. Jordan Anastasiade Java Programming Language Course

CS1020 Data Structures and Algorithms I Lecture Note #8. Exceptions Handling exceptional events

F I N A L E X A M I N A T I O N

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

Exception Handling. General idea Checked vs. unchecked exceptions Semantics of... Example from text: DataAnalyzer.

For more details on SUN Certifications, visit

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

Transcription:

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 and Annotations Keep in Mind

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

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.

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.

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

Introduction 7 How to make our program robust?

Introduction (How to deal with exceptions?) 8 Practice Examples #1: Use of if statement @ 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?

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

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

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

Exception Handling 12 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;

Exception Handling 13 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.

Exception Handling 14 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

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

Exception Handling 16 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.

Exception Handling 17 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

Practice Example #2 18 Read from a file using Scanner and File classes @see Student.java and ReadStudentNames.java

Practice Example #3 19 Write in a file using File and PrintStream classes @see Student.java and ReadWriteStudentNames.java

Common Exceptions 20 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

Common Exceptions 21 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

Common Exceptions 22 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

Throwing Exceptions 23 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

Throwing Exceptions with Methods 24 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. All exceptions declared using throws keyword are turned into checked exceptions that should be handled.

Throwing Exceptions with Methods 25 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 method() 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.

Throwing Exceptions with Methods 26 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

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

Practice Example #4 28 Throwing Exceptions @ see QuadraticEquation.java

Try-with-resources statement 29 (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{ }

Try-with-resources statement 30 (Optional) Practice Example #5 @see TryStatementDemo.java

Assertions and Annotations (optional) 31 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 >;

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

Assertions (optional) 33 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.

Assertions (optional) 34 Example of use of assertions @see Practice Example #4 realrootsolverbis() method related to QuadraticEquation.java

Assertions versus Exceptions (optional) 35 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

Annotations (optional) 36 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

Annotations (optional) 37 Examples of Standard Annotations (other than comments) @Override 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. Example @Override public void tostring() {... } If there is no "tostring()" method in any superclass, then the compiler can issue an error. @Override 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

Annotations (optional) 38 Examples of Standard Annotations (other than comments) @Deprecated 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 code. @Deprecated <item> allows a compiler to generate warnings when the deprecated item is used

Annotations (optional) 39 @SurpressWarnings @SuppressWarnings(<Class 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. Example @SuppressWarnings("deprecation") no warnings about the use of deprecated items will be emitted when the class or method is compiled.

Keep in Mind 40 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

Keep in Mind 41 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 a @throws declaration to your method comment and to describe the situations that can cause the exception

Keep in Mind 42 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.

Keep in mind 43 Java Exceptions Hierarchy Diagram