Lecture 19 Programming Exceptions CSE11 Fall 2013

Similar documents
Exception handling in Java. J. Pöial

BBM 102 Introduction to Programming II Spring Exceptions

More on Exception Handling

More on Exception Handling

BBM 102 Introduction to Programming II Spring 2017

Chapter 13 Exception Handling

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

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

Exception Handling. Exception Handling

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

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

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

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

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

Introductory Programming Exceptions and I/O: sections

CS 3 Introduction to Software Engineering. 3: Exceptions

CS159. Nathan Sprague

Programming II (CS300)

Chapter 12 Exception Handling

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

ECE 122. Engineering Problem Solving with Java

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CSCI 261 Computer Science II

Exceptions Handling Errors using Exceptions

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

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

Input-Output and Exception Handling

Introduction Unit 4: Input, output and exceptions

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

C16b: Exception Handling

Programming II (CS300)

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

EXCEPTION HANDLING. Summer 2018

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

Java Basics: Part 3 - Exceptions. Manuel Oriol

CSC 1214: Object-Oriented Programming

Correctness and Robustness

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

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

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

ITI Introduction to Computing II

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

Object-Oriented Programming in the Java language

Exceptions. CSC207 Winter 2017

What are Exceptions?

File I/O and Exceptions

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

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

CS159. Nathan Sprague

Streams and File I/O

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

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

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

Data Structures. 02 Exception Handling

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

Errors and Exceptions

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

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

Exception-Handling Overview

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

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

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

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

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

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

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

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

Input, Output and Exceptions. COMS W1007 Introduction to Computer Science. Christopher Conway 24 June 2003

Motivations. Chapter 12 Exceptions and File Input/Output

Streams and File I/O

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

Lecture 14 Summary 3/9/2009. By the end of this lecture, you will be able to differentiate between errors, exceptions, and runtime exceptions.

COMP1008 Exceptions. Runtime Error

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

Computer Science is...

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

COMP-202 Unit 9: Exceptions

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

Defensive Programming. Ric Glassey

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

Full file at Chapter 2 - Inheritance and Exception Handling

C17: File I/O and Exception Handling

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

Internal Classes and Exceptions

To Think About. MyClass.mogrify(new int[] { 1, 2, 4, 6 }));

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

17. Handling Runtime Problems

Sri Vidya College of Engineering & Technology Question Bank

School of Informatics, University of Edinburgh

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

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

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

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

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

EXCEPTIONS. Java Programming

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

COMP-202 Unit 9: Exceptions

Transcription:

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: 2 at TestWNS.main(TestWNS.java:14) String Index out of Bounds Null Pointers <-- what does this mean? String format exceptions These are called Exceptions They are logic or other kind errors in your program

Throwing and Catching Exceptions An exception is an object in java A method can generate an exception and tell whomever has invoked it This is called throwing an exception methods throw exceptions, classes do not A method can also intercept an exception and process (handle) it without the program failing. This is an exception handler The method is said to catch the exception

try... catch A block of code can be tried if NO exceptions occur, the catch block (exception handler) is not invoked if an exception happens that is defined in the catch block(s), the program can gracefully handle the exception. try {... code under normal circumstances } catch (Exception e) {... code that executes when exception of type Exception occurs };

A Very Simple Exception Handler import java.util.*; public class SimpleException { public static void main(string[] args) { Scanner parser=new Scanner(System.in); String input; String [] vals; System.out.println("Enter numbers: \n"); try { while ((input = parser.nextline())!= null) { System.out.format("I read number: %f \n", Double.parseDouble(input)); } } } } catch (NoSuchElementException err) {}; handles when we no more input. Not bad numbers

What happens when we type in a bad number $ java SimpleException Enter numbers: 123.45 I read number: 123.450000 this is not a number Exception in thread "main" java.lang.numberformatexception: For input string: " at sun.misc.floatingdecimal.readjavaformatstring(floatingdecimal.java:1241) at java.lang.double.parsedouble(double.java:540) at SimpleException.main(SimpleException.java:12) Can we clean this up a bit with a better exception handler? Stack trace: our code on line 12, was calling Double line 540, was calling readjavaformatstring at line 1241

A Digression on Stack Traces What is a stack? it is like a stack of dishes, you can place something on top (push) You can remove only the top item (pop) you can tell when the stack is empty (but not how tall it is) push new element top new top after push new top after pop pop new element bottom top

The Call Stack Every time a method is invoked (called), a record of that call is placed on the call stack Local variables are allocated from the stack, too Nothing below the top can return until the top returns. x.readjavaformatstring(); readjavaformatstring() new element parsedouble() main() readjavaformatstring() parsedouble() main() Exception occurred here A print out of the call stack at the time of an exception is call the stack trace

A Recursive Call Stack Same thing happens with recursive calls, you just have many copies on the call stack When the recursion hits the base case, the calls below it can return one-by-one recursivemethod(); recursivemethod() new element recursivemethod() recursivemethod() main() recursivemethod() recursivemethod() recursivemethod() recursivemethod() main() base case Each return removes the call from the call stack

Modified Simple Exception Handler import java.util.*; public class SimpleException2 { public static void main(string[] args) { Scanner parser=new Scanner(System.in); String input =""; String [] vals; System.out.println("Enter numbers: \n"); try { while ((input = parser.nextline())!= null) { System.out.format("I read number: %f \n", } Double.parseDouble(input)); } } catch (NoSuchElementException err) {} catch (NumberFormatException err) { } handles when we no more input. Not bad numbers handles format errors System.out.format("I could not understand '%s' as a number\ System.out.format(" Error '%s' had reason '%s' \n", err.getclass().getname(), err.getmessage());

Multiple Catches for the same try block One can handle multiple exceptions with multiple catch blocks They are processed in the order they are defined The first catch block that matches the exception is the first and only catch block to execute. Rule of thumb: catch specialized errors first and more general errors later Why? Exceptions are Objects and are inherited

Exceptions create an inheritance Hierarchy HIGHEST Level view (Important for Checked vs. Unchecked Exceptions) Object Throwable Error Exception RunTimeException

Exceptions create an inheritance Hierarchy HIGHEST Level view (Important for Checked vs. Unchecked Exceptions) Object Throwable Error Exception RunTimeException

What are some Throwable s under the Error Class VirtualMachineError ( Java Interpreter runtime) OutOfMemoryError StackOverflowError AWTError (Problems with AWT Engine) LinkageError (Problems with finding other classes) NoClassDefError ClassFormatError Generally, System errors. Usually, we don't catch these errors

What are Some Runtime Exceptions ArithmeticException ArrayStoreException ClassCastException EmptyStackException IllegalArgumentException IllegalParameterException IllegalThreadStateException NumberFormatException IndexOutOfBoundsException MissingResourceException NegativeArraySizeException NoSuchElementException NullPointerException RasterFormatException SecurityException SystemException UndeclaredThrowableException UnsupportedOperationException

Some Runtime Exceptions RuntimeException ArithmeticException IllegalArgumentException IndexOutOfBoundsException NumberFormatException ArrayIndexOutOfBoundsException StringIndexOutOfBoundsException

Are there other reasons to program with Exceptions? Yes! It can be much simpler to program the main logic of the code WITHOUT testing for all special cases at every step Then catch exceptions when they occur Basic idea is the code runs properly most of the time, and code logic should favor getting the common case right (and debugged)

Checked vs. Unchecked Exceptions Java exception classes are categorized as either "checked" or "unchecked". categorization affects compile-time behavior only; Exceptions are handled identically at runtime. Java determines determine in which category each exception is defined. An unchecked exception is any class that IS A SUBCLASS of RuntimeException (as well as RuntimeException itself). A checked exception is any class that is NOT A SUBCLASS of RuntimeException.

Some Checked Exceptions IOException ChangedCharSetException CharConversionException EOFException FileNotFoundException InterruptedIOException MalformedURLException ObjectStreamException ProtocolException RemoteException TooManyListenersException UnsupportedAudioFileException

Java Complains about Checked Exceptions With unchecked exceptions, we don't have to do anything, they will propagate If one calls (invokes) methods that throw checked exceptions The caller. i.e., the code that invokes the method that throws a checked exception must either explicitly catch the checked exception (re)throw the exception via throws method modifier It's a compiler error if you do NOT catch or rethrow a Checked Exception.

finally not covered in book A finally clause always executes after try...catch block. Enables clean-up processing after either normal operation OR an exception has occurred The default finally block is empty Always Executes try {... normal code } catch (ExceptionClass1 err) {... exception code } catch (ExceptionClass2 err) {... exception code } finally {... clean up code };

Some clarifying exercises Is there anything wrong with the following exception handler as written? Will this code compile? try { } catch (Exception e) { } catch (ArithmeticException a) { } What exception types can be caught by the following handler? catch (Exception e) { } What is bad about using this type of exception handler?

The Concept of a Stream Use of files Store Java classes, programs Store pictures, music, videos Can also use files to store program I/O A stream is a flow of input or output data Characters Numbers Bytes

The Concept of a Stream Streams are implemented as objects of special stream classes Class Scanner Object System.out

3 Streams in Unix Standard input (stdin in C) Standard output (stdout in C) Standard error (stderr in C) These are available in the unix shell % program < inputfile Send the input file as the stdin to the program % program > outputfile Send the output of a program to a file % program1 program2 Send the output of program1 to the input of program2 (this is called a pipe)

Why Use Files for I/O Keyboard input, screen output deal with temporary data When program ends, data is gone Data in a file remains after program ends Can be used next time program runs Can be used by another program

Text Files and Binary Files All data in files stored as binary digits Long series of zeros and ones Files treated as sequence of characters called text files Java program source code Can be viewed, edited with text editor All other files are called binary files Movie, music files Access requires specialized program

Text Files and Binary Files

Creating a Text File Class PrintWriter defines methods needed to create and write to a text file Must import package java.io To open the file Declare stream variable for referencing the stream Invoke PrintWriter constructor, pass file name as argument Requires try and catch blocks

Creating a Text File File is empty initially May now be written to with method println Data goes initially to memory buffer When buffer full, goes to file Closing file empties buffer, disconnects from stream

Creating a Text File When creating a file Inform the user of ongoing I/O events, program should not be "silent" A file has two names in the program File name used by the operating system The stream name variable Opening, writing to file overwrites pre-existing file in directory