CS Programming I: Exceptions

Similar documents
CS Programming I: 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

CS Programming I: Arrays

Exception-Handling Overview

CS Programming I: ArrayList

BBM 102 Introduction to Programming II Spring Exceptions

Object Oriented Programming

CS Programming I: Primitives and Expressions

CS Programming I: File Input / Output

CS159. Nathan Sprague

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

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

CS Programming I: File Input / Output

BBM 102 Introduction to Programming II Spring 2017

Introduction to Software Design

CS Programming I: Inheritance

CS Programming I: Programming Process

CS Programming I: Programming Process

CS Programming I: Programming Process

ECE 122. Engineering Problem Solving with Java

More on Exception Handling

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

More on Exception Handling

COMP1008 Exceptions. Runtime Error

6.Introducing Classes 9. Exceptions

CS Programming I: Branches

Data Structures. 02 Exception Handling

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

Comp 249 Programming Methodology Chapter 9 Exception Handling

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

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

Exceptions. COMP 202 Exceptions. Exceptions. Exceptions. An exception is an object that describes an unusual or erroneous situation

Chapter 12 Exception Handling

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

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

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

CS Programming I: Branches

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

CSCI 261 Computer Science II

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

ITI Introduction to Computing II

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

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

CS159. Nathan Sprague

ITI Introduction to Computing II

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Exceptions - Example. Exceptions - Example

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

CS Programming I: Using Objects

CS Programming I: Classes

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

EXCEPTIONS. Fundamentals of Computer Science I

CS Programming I: Using Objects

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

Chapter 13 Exception Handling

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

Exceptions. CSC207 Winter 2017

Object Oriented Programming

Fundamentals of Object Oriented Programming

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

Program Correctness and Efficiency. Chapter 2

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

CSC 1214: Object-Oriented Programming

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

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

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

Programming II (CS300)

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

Object Oriented Programming Exception Handling

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

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

Lecture 19 Programming Exceptions CSE11 Fall 2013

Contents. I Introductory Examples. Topic 06 -Exception Handling

Advanced Java Concept Unit 1. Mostly Review

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

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

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

C16b: Exception Handling

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

CS 3 Introduction to Software Engineering. 3: Exceptions

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

Motivations. Chapter 12 Exceptions and File Input/Output

CS 209 Programming in Java #10 Exception Handling

What are Exceptions?

Recitation 3. 2D Arrays, Exceptions

Programming II (CS300)

Excep&ons and file I/O

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

Java Exception. Wang Yang

EXCEPTION HANDLING. Summer 2018


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

COMP-202 Unit 9: Exceptions

Exceptions Handling Errors using Exceptions

COMP-202 Unit 9: Exceptions

Java Errors and Exceptions. Because Murphy s Law never fails

Transcription:

CS 200 - Programming I: Marc Renault Department of Computer Sciences University of Wisconsin Madison Spring 2018 TopHat Sec 3 (AM) Join Code: 427811 TopHat Sec 4 (PM) Join Code: 165455

Command-Line Arguments

1/29 Passing Command-Line Arguments Example: java CmdLineEx arg0 agr1 arg2 Command-Line Arguments Arguments passed to the program when it is launched. In example: arg0, arg1, arg2

1/29 Passing Command-Line Arguments Example: java CmdLineEx arg0 agr1 arg2 Command-Line Arguments Arguments passed to the program when it is launched. In example: arg0, arg1, arg2 String[] args Passed to the main method via the String[] args. In example: String[] args = {"arg0","arg1","arg2".

2/29 TopHat Question 1 What is the output when executed using the command java CmdLineEx Do or do not, there is no try. public class CmdLineEx { public static void main ( String [] args ) { int i = 0; for ( String s: args ) { i += s. length (); System. out. print (i);

3/29 Command-Line Argument Exercise Write a program that receives from the command line both a string and action to perform (either changing to upper case or lower case). The command-line arguments are organized as follows: -s str, where str is the string to transform -l to lowercase -u to uppercase There should only be one of -l or -u. The arguments should be handled in any order. After parsing the arguments, the program outputs the string, having converted to upper or lower case as per the command-line arguments.

4/29 What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program.

4/29 What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running.

4/29 What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error.

4/29 What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error. A user goes off the happy path.

4/29 What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program. What causes these events? A failure of the machine where the program is running. A programming error. A user goes off the happy path. Why use exceptions? Separates error-checking from normal happy path code. Organized with try-catch-finally and throws.

5/29 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

6/29 Errors Causes Errors are caused by abnormal conditions beyond the control of the programmer causing the program to fail such as hardware failures. Some Examples java.io.ioerror java.lang.outofmemoryerror java.lang.linkageerror

7/29 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

8/29 Runtime Exception Causes Runtime are typically caused by programming errors (bugs) not caught at compile time such as trying to access an out of bounds cell in an array. Some Examples java.lang.nullpointerexception java.lang.indexoutofboundsexception java.lang.arrayindexoutofboundsexception java.lang.stringindexoutofboundsexception java.lang.arithmeticexception

9/29 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

9/29 Java Exception Hierarchy Object Throwable Error Exception... Unchecked Runtime......

9/29 Java Exception Hierarchy Object Throwable Error Checked Exception... Unchecked Runtime......

10/29 Unchecked vs Checked Unchecked Exception An unchecked exception is an exceptional condition that the application usually cannot anticipate or recover from. These are: Errors Runtime exceptions

10/29 Unchecked vs Checked Unchecked Exception An unchecked exception is an exceptional condition that the application usually cannot anticipate or recover from. These are: Errors Runtime exceptions Checked All other exceptions are checked exceptions. A method must handle all checked exceptions by either: Using a try-catch block, or Throwing the exception.

11/29 TopHat Question 2 What kind of exception is java.util.inputmismatchexception? The following code compiles. When the user inputs a, the program terminates with a java.util.inputmismatchexception. import java. util. Scanner ; public class ExceptionEx1 { public static void main ( String [] arg ) { Scanner sc = new Scanner ( System. in ); int a = sc. nextint (); System. out. println (" Value is " + a);

12/29 try-catch try { trystmt1 ;... trystmtn ; catch ( AnException e) { catchstmt1 ;... catchstmtn ;

12/29 try-catch try { trystmt1 ;... trystmtn ; catch ( AnException e) { catchstmt1 ;... catchstmtn ; Control Flow Try Stmt Block AnException? No Following statements Yes AnException Catch Block

13/29 TopHat Question 3 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( Exception e) { System. out. print (" Catch."); System. out. print (" Done.");

14/29 Catching the Exact Exception Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( Exception e) { System. out. print (" Catch."); Best Practice When catching exceptions, be as precise as possible about the exception.

14/29 Catching the Exact Exception Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( InputMismatchException e) { System. out. print (" Input was not an integer."); Best Practice When catching exceptions, be as precise as possible about the exception.

15/29 Stack Trace Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. println (" Value is " + a); catch ( InputMismatchException e) { System. out. println (" Input was not an integer."); e. printstacktrace (); Stack Trace Prints the trace of methods calls (with line numbers) on the stack leading to the exception. Throwable has an instance method printstacktrace().

16/29 Basic try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ;

16/29 Basic try-catch-finally Basic Control Flow Try Stmt Block try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; AnException? No Finally Stmt Block Yes AnException Catch Block Following statements

17/29 TopHat Question 4 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); catch ( InputMismatchException e) { System. out. print (" Catch."); finally { System. out. print (" Finally."); System. out. print (" Done.");

18/29 TopHat Question 5 What is the output when the user enters 2? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); catch ( InputMismatchException e) { System. out. print (" Catch."); finally { System. out. print (" Finally."); System. out. print (" Done.");

19/29 Multiple catch try { trystatements ; catch ( Exception1 e) { catch1statements ; catch ( Exception2 e) { catch1statements ;... catch ( ExceptionN e) {

19/29 Multiple catch Control Flow try { trystatements ; catch ( Exception1 e) { catch1statements ; catch ( Exception2 e) { catch1statements ;... catch ( ExceptionN e) { Exception1 Catch Block Try Stmt Block Caught Exception? ExceptionN Catch Block Following statements No

20/29 TopHat Question 6 What is the output when the user enters 0? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( ArithmeticException e) { System. out. print (" Catch Div 0."); finally { System. out. print (" Finally."); System. out. print (" Done.");

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception?

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed.

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? What if the catch block throws an exception? The finally block is still executed.

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? The finally block is still executed. What if the catch block throws an exception? The finally block is still executed.

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block returns? The finally block is still executed. What if the try block returns? What if the catch block throws an exception? The finally block is still executed.

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed.

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed. What if the try block throws an uncaught exception?

21/29 Advanced try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ; What if the catch block throws an exception? The finally block is still executed. What if the catch block returns? The finally block is still executed. What if the try block returns? The finally block is still executed. What if the try block throws an uncaught exception? The finally block is still executed.

22/29 TopHat Question 7 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); System. out. print (" Value is " + a + "."); return ; catch ( InputMismatchException e) { System. out. print (" Catch."); return ; finally { System. out. print (" Finally.");

23/29 Basic Throwing Creating and Using Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg.

23/29 Basic Throwing Creating and Using Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg. Some methods: printstacktrace() Prints the exception stack trace. getmessage() Returns the message associated with the exception.

23/29 Basic Throwing Creating and Using Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg. Some methods: printstacktrace() Prints the exception stack trace. getmessage() Returns the message associated with the exception. Throwing an Exception throw athrowable; Stops normal executions and throws an exception. E.g. throw new Exception("An exception!");

TopHat Question 8 What is the output when the user enters z? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); if(a <= 0) throw new Exception (" Error : Val <= 0."); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( Exception e) { System. out. print (e. getmessage ()); finally { System. out. print (" Finally."); System. out. print (" Done."); 24/29

TopHat Question 9 What is the output when the user enters 0? Scanner sc = new Scanner ( System. in ); try { int a = sc. nextint (); if(a <= 0) throw new Exception (" Error : Val <= 0."); System. out. print (" Value is " + 10/ a + "."); catch ( InputMismatchException e) { System. out. print (" Catch Mismatch."); catch ( Exception e) { System. out. print (e. getmessage ()); finally { System. out. print (" Finally."); System. out. print (" Done."); 25/29

26/29 Methods Throwing Specifying Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional.

26/29 Methods Throwing Specifying Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller.

26/29 Methods Throwing Specifying Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller. The caller can either: Throw the exception further up the stack calls, or

26/29 Methods Throwing Specifying Thrown... somemethod(...) throws exception1,exception2,... Part of the method header. All checked exceptions must be listed. Unchecked ones are optional. Throwing vs Catching A method, somemethod, that throws a checked exception is passing the exception to the caller. The caller can either: Throw the exception further up the stack calls, or Put the method call to somemethod in a try block and handle the exception in a catch block.

27/29 TopHat Question 10 What is the output when the user enters 0? public static void div ( int a, int b) throws Exception { if(b == 0) throw new Exception (" Error : a is 0."); System. out. print (" Value is " + b/a + "."); public static void main ( String [] arg ) { Scanner sc = new Scanner ( System. in ); int a = sc. nextint (); try { div (10, a); catch ( Exception e) { System. out. print (e. getmessage ()); System. out. print (" Done.");

TopHat Question 11 What is the stack trace output when the program runs? 1 public class ExceptionEx11 { 2 3 public static void f() throws Exception { 4 throw new Exception (); 5 6 7 public static void main ( String [] arg ) { 8 try { 9 g (); 10 11 catch ( Exception e) { 12 e. printstacktrace (); 13 14 15 16 public static void g() throws Exception { 17 f (); 18 19 28/29

29/29 Further Reading COMP SCI 200: Programming I zybooks.com, 2015. zybook code: WISCCOMPSCI200Spring2018 Chapter 10.

Appendix References Appendix

Appendix References References

Appendix References 30/29 Image Sources I https://brand.wisc.edu/web/logos/ http://www.zybooks.com/