COMP-202 Unit 9: Exceptions

Similar documents
COMP-202 Unit 9: Exceptions

BBM 102 Introduction to Programming II Spring Exceptions

CONTENTS: Arrays Strings. COMP-202 Unit 5: Loops in Practice

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

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

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

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

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

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

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

COMP-202 Unit 4: Programming with Iterations

Fundamentals of Object Oriented Programming

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

BBM 102 Introduction to Programming II Spring 2017

CS 11 java track: lecture 3

Computer Science is...

CSCI 261 Computer Science II

Warmup : Name that tune!

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

CS159. Nathan Sprague

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

Programming - 2. Common Errors

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

Exception-Handling Overview

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

Introduction Unit 4: Input, output and exceptions

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

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

Intro to Computer Science II. Exceptions

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

Correctness and Robustness

COE318 Lecture Notes Week 10 (Nov 7, 2011)

ECE 122. Engineering Problem Solving with Java

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

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

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

Programming Languages and Techniques (CIS120)

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

Internal Classes and Exceptions

Object Oriented Programming Exception Handling

CMSC 202. Exceptions

EXCEPTIONS. Java Programming

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

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

EXCEPTIONS. Fundamentals of Computer Science I

Warm-Up: COMP Programming with Iterations 1

9. Java Errors and Exceptions

Exceptions and Libraries

CS193j, Stanford Handout #25. Exceptions

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

Exception Handling. Exception Handling

11/1/2011. Chapter Goals

CS159. Nathan Sprague

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

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

COMP-202: Foundations of Programming. Lecture 4: Flow Control Loops Sandeep Manjanna, Summer 2015

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

Introduction to Computation and Problem Solving. Class 25: Error Handling in Java. Prof. Steven R. Lerman and Dr. V. Judson Harward.

Errors and Exceptions

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

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

Programming II (CS300)

Input from Files. Buffered Reader

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Chapter 14. Exception Handling and Event Handling ISBN

What did we talk about last time? Course overview Policies Schedule

Introduction to Computer Science II CS S-22 Exceptions

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Exceptions. CSC207 Winter 2017

14. Exception Handling

Program 12 - Spring 2018

Java Exception. Wang Yang

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

More on Exception Handling

Projeto de Software / Programação 3 Tratamento de Exceções. Baldoino Fonseca/Márcio Ribeiro

Std 12 Lesson-10 Exception Handling in Java ( 1

CS 3 Introduction to Software Engineering. 3: Exceptions

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

An exception is simply an error. Instead of saying an error occurred, we say that an.

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

Exception Handling CSCI 201 Principles of Software Development

Data Structures. 02 Exception Handling

CISC-124. Passing Parameters. A Java method cannot change the value of any of the arguments passed to its parameters.

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

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

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

Typecasts and Dynamic Dispatch. Dynamic dispatch

Programming II (CS300)

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

Documen(ng code, Javadoc, Defensive Programming, Asserts, Excep(ons & Try/Catch

C16b: Exception Handling

6. Java Errors and Exceptions

Chapter 12 Exception Handling

Download link: Java Exception Handling

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

Object Oriented Programming. Week 7 Part 1 Exceptions

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

Transcription:

COMP-202 Unit 9: Exceptions

Announcements - Assignment 4: due Monday April 16th - Assignment 4: tutorial - Final exam tutorial next week 2

Exceptions An exception is an object that describes an unusual or erroneous situation 3

Avoiding errors So far, we have spend most of our time discussing how to avoid errors happening in the first place. However, this is not always possible. 4

Errors out of our control Some errors may happen for reasons beyond our control. For example: -user types a String when he should type an int -a spot on a hard drive is not readable 5

Handling the error In this case, rather than having our program crash, we may want to perform a certain action: -Ask the user to retry entering a new number -Try reading information from a different part of the hard drive 6

Exceptions In Java, an exception occurs when a piece of code does something out of the ordinary or exceptional You would like to have special behavior in these cases. 7

Exceptions : definition From the documentation: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. 8

Example of Exception Some examples of things that can disrupt the normal flow of a program: -NullPointerException (trying to access properties of a null variable) -ArrayIndexOutOfBoundsException (trying to access spots of an array that don't exist) -Dividing by zero -NumberFormatException (trying to, for example, convert a String to a number) 9

Why does it interrupt? All of these examples interrupt the normal flow because you can't proceed any further without any further instructions as to what to do: int[] x = {1, 2, 3; int foo = x[10]; //assign to foo the 10th index spot System.out.println(foo); array out of bounds 10

Unhandled exceptions By default, if you have an Exception in Java, the exceptional event is unhandled. This means that you are not handling the exception meaning the computer doesn't know what to do. When the computer doesn't know what to do, it crashes. 11

Handling exceptions There is a block of code in Java known as a try/catch block: A try/catch block allows you to try certain code, and if an exception is raised, you can then catch the exception. 12

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); 13

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); Here we will first try to execute the commands inside the try statement. 14

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); If the commands succeed and don't raise an exception, we will then finish the try block and skip the catch block completely. 15

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); If the commands inside the try block raise an exception, and the exception is an ArrayIndexOutOfBounds exception, we skip to the catch block. 16

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); After the catch block, we proceed normally with our program. (Although any variables created in the try block are now out of scope of course) 17

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); If an exception happens, but the exception is NOT an ArrayIndexOutOfBoundsException, then this method will throw the exception back to the method that called it. 18

Example: try { int[] x = {1,2,3; System.out.println(x[10]); catch (ArrayIndexOutOfBoundsException e) { System.out.println( This is the code that handles the exception ); This means that the method that called this method would have an opportunity to handle (catch) the exception. 19

Exceptions in a method Generally, when an exception occurs in a method, 2 things can happen: 1)The method catches or handles the exception 2)The method does not catch or handle the exception and instead passes the exception on to the method that called it. In the case of it being the main method, the program then crashes (since there is no method to pass the exception on to). 20

try/catch/finally In addition to try/catch, you can also have a block of code that will happen in both cases. This serves two purposes: 1)Removes duplicate code 2)Lets you clean up things before crashing or returning. The second one is very useful. Let's say I use lots of resources in my code and I have many return statements as well. I can use a finally statement to make sure it is indeed cleaned up. 21

try/catch/finally try { //do some stuff if (some condition) { return; catch (Exception e) { finally { //clean up ----> This code happens after the return 22

try/finally try { //do some stuff if (some condition) { return; finally { //clean up ----> This code happens after the return In fact, in many cases you don't even need the catch part. 23

Example class Test { public static void main(string args[]) { System.out.println(Test.test()); public static int test() { try { return 0; finally { System.out.println("finally trumps return."); 24

Example class Test { public static void main(string args[]) { System.out.println(Test.test()); public static int test() { try { return 0; finally { System.out.println("finally trumps return."); output: finally trumps return. 0 25

Multiple catch blocks Sometimes, there may be several possible errors you could have. You can then have several exception handlers. In this case only the FIRST exception handler that is applicable will be used: try {... catch (ArrayIndexOutOfBoundsException e) {... catch (NullPointerException e) {... 26

Rewriting Fahrenheit converter Let's rewrite our Fahrenheit converter to let the user retry entering a number instead of crashing. 27

Rewriting Fahrenheit converter public class FahrenheitConverter { public static void main(string[] args) { double number; boolean initialized = false; Scanner reader = new Scanner(System.in); while (!initialized) { try { System.out.println( Enter a number ); number = reader.nextdouble(); initialized = true; catch (InputMismatchException e) { System.out.println( You idiot, that's not a number! ); reader.next(); //need to skip over the thing that failed to be read... 28

Rewriting Fahrenheit converter Here we use the variable initialized to control a loop that continues to repeat trying to read from the scanner until the try block can complete successfully. If there is an exception and the kind of exception is InputMismatchException, then the program goes into the catch block of code which stops it from crashing. 29

Mandatory Exception Handling Some methods will warn you that they will throw an exception. In this case the method header will show up with a throws kindofexception in it: For example, the header for creating a Scanner is public Scanner(File source) throws FileNotFoundException 30

Mandatory Exception Handling public Scanner(File source) throws FileNotFoundException This is a warning that the constructor sometimes throws a FileNotFoundException and so you HAVE to handle/catch the exception. If you do not, you will get a compiler error. 31

Mandatory Exception Handling So if I want to call this method, there are 2 things I could do to handle the exception: 1)Put it into a try / catch statement 2)Warn any method calling the method I'm in now, that the current method also throws a FileNotFoundException sometimes. I can do the second by writing throws FileNotFoundException in my method header. 32

Creating a search engine (a small piece) -One of the key aspects to creating a search engine like Google or Bing is to go to, given a list of urls, download the HTML data on that page and then try to figure out what the page is about. -In order to do this, it is useful to write a method that takes as input a list of urls and outputs a String[] of their data. 33

Creating a search engine (a small piece) Given a file that contains a list of urls: 1)Read the file and get all of the urls 2)Download the urls. Get the information downloaded and store it into a String. What if that file is corrupted or contains a bad url? 34

Creating a search engine (a small piece) Since that file contains contents OUT OF YOUR CONTROL, you need to catch any exceptions. For example, if download the page leads to an error, then you should NOT have your program crash. What it would be better to do is output the information to some sort of log file so that you can learn about the error. 35

Creating a search engine (a small piece) String[] urls = readalllinesoffile(filename); String[] htmldata = new String[urls.length]; for (int i = 0; i<urls.length; i++) { htmldata[i] = WebUtilities.downloadPage(urls[i]); return htmldata; The problem is that sometimes downloadpage has an exception! Let's say the url is http://http://www.amazon.com 36

Much better way to do this for (int i = 0; i<urls.length; i++) { try { htmldata[i] = WebUtilities.downloadPage(urls[i]); catch (PageNotFoundException e) { htmldata[i] = ; System.out.println( The page + urls[i] + was not found );... Now if there is a bad url it won't crash your program! 37

Example Explanation (1) why public static String downloadpage(string url) throws MalformedURLException, IOException

Example Explanation (2) why public static String downloadpage(string url) throws MalformedURLException, IOException

Java vs other languages In Java, if the method downloadpage throws an exception you would HAVE to either: 1)Catch the exception 2)Warn anyone calling your method that YOU may throw an exception as well. This means you HAVE to at least acknowledge this sort of exception can occur. 40

Java vs other languages In Java, this means a hypothetical method like downloadpage would have to warn the user that it is throwing an exception sometimes. This means the user will handle the code appropriately. In other languages, this is not always the case, and can lead to problems. In fact, this led to a major issue a search engine recently because just ONE url (out of millions) in this sort of file was corrupted. The entire system went down because of this. 41

Throwing an exception Sometimes, your method will want to throw an exception to another method and there it can be printed. For example, in many of the methods we've written we have made certain assumptions about things. But when the assumption does not hold, you may want your program to still work then, but give an exception to the calling method to allow them to decide what to do. In this case, you will throw an exception. 42

Exceptions as a type An Exception is an Object. It can be created via using a constructor and in fact in the parenthesis of a catch statement, when we write catch (Exception e) we are actually declaring a variable e of type Exception. There are many ways to create an Exception in Java, one of which is using the constructor that takes as input one String, representing a message new Exception( Here is some information about the exception ); 43

Exceptions as a type Then to throw an exception, you write the word throw followed by the Exception object: e.g. throw new Exception( Message ); In many cases (it depends on the exact kind of Exception you are throwing), you'll then have to warn methods calling you that you will sometimes throw an exception (by putting throws in the method header) 44

Throwing an exception public class FakeNullPointer { public static void main(string[] args) { throw new NullPointerException( x is null! ); D:\Teaching\COMP202\Lectures_Xue\unit9>java FakeNullPointer Exception in thread "main" java.lang.nullpointerexception: x is null at FakeNullPointer.main(FakeNullPointer.java:3) 45

Throwing an exception If you throw an exception, you must warn anyone calling your method that you will throw an exception sometimes by adding throws TypeOfException into your method header (Side Note:) Unless it is an runtimeexception. You can see this by looking at the documentation of the type of exception and seeing if runtimeexception is part of the class hierarchy 46

Creating your own Exception types You can define your own exception types. This is useful if you have a very particular kind of problem, but you don't want to deal with it all over your code. For example, suppose you are managing a BankAccount. One of the things you may have to deal with is the user trying to withdraw more money than he has. Unless the use is the Wall Street, you'd like to throw an exception in this case, to stop it. There is no NotEnoughMoneyException built in, so you could define it. 47

What to know: We only covered the very basics of exception handling. What you are responsible for is the following: -What an exception is -The flow of a try/catch block and what happens if you don't handle or catch an Exception (it gets thrown up to the method that called it which then must either handle it or throw it further up the chain of commands, until you reach the main method at which point the program crashes) -Recognize from method headers that you NEED to put something into a try/catch 48

That's all! That's all the material we need to cover for this course. 49