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

Similar documents
Chapter 12 Exception Handling

Chapter 13 Exception Handling

Exception-Handling Overview

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

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

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

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

Motivations. Chapter 12 Exceptions and File Input/Output

BBM 102 Introduction to Programming II Spring Exceptions

BBM 102 Introduction to Programming II Spring 2017

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

Correctness and Robustness

Data Structures. 02 Exception Handling

CS159. Nathan Sprague

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

Programming II (CS300)

ECE 122. Engineering Problem Solving with Java

Programming II (CS300)

CSCI 261 Computer Science II

EXCEPTION HANDLING. Summer 2018

CS159. Nathan Sprague

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

Java Errors and Exceptions. Because Murphy s Law never fails

CSC 1214: Object-Oriented Programming

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

Exceptions and Error Handling

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

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

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

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

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

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

Full file at Chapter 2 - Inheritance and Exception Handling

Std 12 Lesson-10 Exception Handling in Java ( 1

Comp 249 Programming Methodology Chapter 9 Exception Handling

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

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Exceptions - Example. Exceptions - Example

Exceptions Handling Errors using Exceptions

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

16-Dec-10. Consider the following method:

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

CS 209 Programming in Java #10 Exception Handling

Chapter 11 Handling Exceptions and Events. Chapter Objectives

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

Introductory Programming Exceptions and I/O: sections

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

Why Exceptions? (1.1) Exceptions. Why Exceptions? (1.2) Caller vs. Callee. EECS2030 B: Advanced Object Oriented Programming Fall 2018

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

Exceptions. EECS2030 B: Advanced Object Oriented Programming Fall 2018 CHEN-WEI WANG

11/1/2011. Chapter Goals

More on Exception Handling

Object Oriented Programming Exception Handling

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

COE318 Lecture Notes Week 10 (Nov 7, 2011)

COMP-202 Unit 9: Exceptions

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

ITI Introduction to Computing II

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

COMP-202 Unit 9: Exceptions

Fundamentals of Object Oriented Programming

Exception Handling. Chapter 9

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

ITI Introduction to Computing II

More on Exception Handling

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

17. Handling Runtime Problems

Intro to Computer Science II. Exceptions

Typecasts and Dynamic Dispatch. Dynamic dispatch

Introduction Unit 4: Input, output and exceptions

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

What can go wrong in a Java program while running?

For more details on SUN Certifications, visit

Programming Languages and Techniques (CIS120)

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

What are Exceptions?

Input-Output and Exception Handling

Introduction to Software Design

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

WOSO Source Code (Java)

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

Exception Handling Advanced Programming Techniques

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

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling

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

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

Chapter 11 Exception Handling

Programming - 2. Common Errors

CSE 143 Java. Exceptions 1/25/

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

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Making New instances of Classes

Errors and Exceptions

C16b: Exception Handling

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

Exception Handling. Chapter 8. Chapter 8 1

Transcription:

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 and what is exception handling To declare exceptions in the method header To throw exceptions out of a method To write a try-catch block to handle exceptions CS115 ExceptionHandling.2

Syntax Errors, Runtime Errors, and Logic Errors There are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because the rules of the language have not been followed. They are detected by the compiler. Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out. Logic errors occur when a program doesn't perform the way it was intended to. CS115 ExceptionHandling.3 An Example of Runtime Errors 1 import java.util.scanner; 2 3 4 5 6 y p ( g ); 7 8 9 10 11 12 13 If an exception occurs on this line, the rest of the lines in the method are skipped and the program is terminated. Terminated. public class ExceptionDemo { public static void main(string[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter an integer: "); int number = scanner.nextint(); // Display the result System.out.println( "The number entered is " + number); What if the user enters a floating-point number? Run CS115 ExceptionHandling.4

Exception Handling Exceptions occur for various reasons ArrayIndexOutOfBoundException: if we want to access an array element past the end of the array. NullPointerException: if we want to invoke a method on a reference variable with null value StringIndexOutOfBoundException: if we want to access a character in a string using an out-of-bound index FileNotFoundException: open a file that doesn t exist IllegalArgumentException: a method is passed an argument that is illegal or inappropriate Many more Exception handling is to develop robust programs for missioncritical applications CS115 ExceptionHandling.5 Catch Runtime Errors 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 If an exception occurs on this line, the rest of lines in the try block are skipped and the control is transferred to the catch block. import java.util.*; public class HandleExceptionDemo { public static void main(string[] args) { Scanner scanner = new Scanner(System.in); boolean continueinput = true; do { System.out.print("Enter an integer: "); int number = scanner.nextint(); // Display the result System.out.println( "The number entered is " + number); Run continueinput = false; catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextline(); // discard input while (continueinput); CS115 ExceptionHandling.6

Exception Classes Exceptions are represented in the Exception class in Java System errors are represented in the Error class, not our business Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program. Exception ClassNotFoundException IOException AWTException ArithmeticException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes Error VirtualMachineError AWTError We can create own exception classes by extending Throwable! Several more classes CS115 ExceptionHandling.7 Java Exception Handling Model Three operations: declaring an exception, throwing an exception, and catching an exception Keywords: throw and throws catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception CS115 ExceptionHandling.8

Declaring Exceptions Every method must state the types of exceptions it might throw. This is known as declaring exceptions. public void mymethod()throws IOException public void mymethod() throws IOException, OtherException // if the method might throw multiple exceptions catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throwexception CS115 ExceptionHandling.9 Throwing Exceptions When the program detects an error, it can create an instance of an appropriate exception type and throw it, known as throwing an exception one throw statement can only throw one exception though one method can throw multiple exceptions Here is an example, throw new IllegalArgumentException( Wrong Argument ); or IllegalArgumentException ex = new IllegalArgumentException( Wrong Argument ); throw ex; catch exception method1() { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception CS115 ExceptionHandling.10

Throwing Exceptions Example demonstrates exception declaring and throwing by modifying setradius in the Circle3 class. /** Set a new radius */ public void setradius(double newradius) throws IllegalArgumentException { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException( "Radius cannot be negative"); The argument is called the exception message, which can be obtained using getmessage(). CS115 ExceptionHandling.11 Catching an Exception statements; // Statements that may throw exceptions catch (Exception1 exvar1) { handler for exception1; catch (Exception2 exvar2) { handler for exception2; catch (ExceptionN exvar3) { handler for exceptionn; What about catching an exception in chained methods invoking? main method { invoke method1; statement1; catch (Exception1 ex1) { Process ex1; statement2; method1 { invoke method2; statement3; catch (Exception2 ex2) { Process ex2; statement4; method2 { invoke method3; statement5; catch (Exception3 ex3) { Process ex3; statement6; An exception is thrown in method3 CS115 ExceptionHandling.12

Exception Handling Example demonstrates exception handling by modifying setradius in the Circle3 class. public class CircleWithException { public CircleWithException(double newradius) { setradius(newradius); public void setradius(double newradius) throws IllegalArgumentException g { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException("Radius cannot be negative"); CircleWithException public class TestCircleWithException { public static void main(string[] args) { What if removing try catch block? CircleWithException c1 = new CircleWithException(5); CircleWithException c2 = new CircleWithException(-5); CircleWithException c3 = new CircleWithException(0); catch (IllegalArgumentException ex) { TestCircleWithException System.out.println(ex); System.out.println("Number of objects created: " + CircleWithException.getNumberOfObjects()); CS115 ExceptionHandling.13 Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b). void p1() { p2(); catch (IOException ex) { (a) void p1() throws IOException { p2(); (b) CS115 ExceptionHandling.14 14

Creating Own Exception Classes What to do if we a method needs an exception object not available in the standard Exception class? Derive own exception class from one the in the Exception hierarchy public class SpecialFileException extends IOException { // Throws exception if file contains letter 'Z' // Constructors public SpecialFileException () { public SpecialFileException (String message) { super(message); public class SomeApplication { public String readspecialdata(bufferedreader in) throws SpecialFileException { // Throws exception if file contains letter 'Z' while ( ) { if (ch == 'Z') // character 'Z' encountered throw new SpecialFileException("Z encountered"); CS115 ExceptionHandling.15 The finally Clause What to do if we want some code to be executed regardless of whether an exception occurs or is caught? If no exception arises in the try block If one of the try statements courses an exception and caught in a catch block w/ or w/o exception rethrowing If one of the try statements t t courses an exception and NOT caught in a catch block then passed to the method caller The finally block executes even if there is a return statement prior to reaching the finally block statements; catch(theexception ex) { handling ex; finally { finalstatements; statementaftertry; CS115 ExceptionHandling.16

Program Execution Example I What would be the printout if the line int value = 30; is changed to int value = 50; CS115 ExceptionHandling.17 Program Execution Example II CS115 ExceptionHandling.18

When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example: System.out.println(refVar.toString()); i catch (NullPointerException ex) { System.out.println("refVar is null"); if (refvar!= null) System.out.println(refVar.toString()); else System.out.println("refVar is null"); CS115 ExceptionHandling.19 Reading Chapter 17 of the textbook: 17.1 17.5 Preview Chapter 11 OOD Do review questions: 17.4, 17.6-17.13, 17.18-17.19 CS115 ExceptionHandling.20