CS Programming I: Exceptions

Similar documents
CS Programming I: Exceptions

CS Programming I: File Input / Output

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: File Input / Output

CS Programming I: Arrays

Object Oriented Programming

CS Programming I: Inheritance

Exception-Handling Overview

BBM 102 Introduction to Programming II Spring Exceptions

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

CS Programming I: ArrayList

6.Introducing Classes 9. Exceptions

CS Programming I: Programming Process

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

CS159. Nathan Sprague

BBM 102 Introduction to Programming II Spring 2017

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

CS Programming I: Primitives and Expressions

Comp 249 Programming Methodology Chapter 9 Exception Handling

COMP1008 Exceptions. Runtime Error

Data Structures. 02 Exception Handling

Introduction to Software Design

CS Programming I: Branches

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

ECE 122. Engineering Problem Solving with Java

More on Exception Handling

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

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

More on Exception Handling

CS Programming I: Programming Process

CS Programming I: Programming Process

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

Chapter 12 Exception Handling

CS Programming I: Branches

CSCI 261 Computer Science II

ITI Introduction to Computing II

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

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

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

ITI Introduction to Computing II

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

Exceptions - Example. Exceptions - Example

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

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

CS159. Nathan Sprague

CS Programming I: Classes

Chapter 13 Exception Handling

EXCEPTIONS. Fundamentals of Computer Science I

CS Programming I: Using Objects

Programming II (CS300)

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Program Correctness and Efficiency. Chapter 2

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

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

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

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Lecture 19 Programming Exceptions CSE11 Fall 2013

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

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

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

CSC 1214: Object-Oriented Programming

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

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

CS Programming I: Using Objects

Exceptions. CSC207 Winter 2017

Object Oriented Programming

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

Contents. I Introductory Examples. Topic 06 -Exception Handling

Fundamentals of Object Oriented Programming

Motivations. Chapter 12 Exceptions and File Input/Output

Java Exception. Wang Yang

C16b: Exception Handling

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

The University of Melbourne Department of Computer Science and Software Engineering Software Design Semester 2, 2003

Exceptions. Why Exception Handling?

CS 3 Introduction to Software Engineering. 3: 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

Chapter 3 Java Exception

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

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

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

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

Object Oriented Programming Exception Handling

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

Exceptions and Libraries

Java Errors and Exceptions. Because Murphy s Law never fails

What are Exceptions?

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Excep&ons and file I/O

Advanced Java Concept Unit 1. Mostly Review

Exceptions Handling Errors using Exceptions

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

EXCEPTION HANDLING. Summer 2018

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

CS 200 Command-Line Arguments & Exceptions Jim Williams, PhD

Programming II (CS300)

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

Transcription:

CS 200 - Programming I: Exceptions Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624

Command-Line Arguments

1/31 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/31 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/31 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/31 Command-Line Argument Exercise Write a program that receives from the command line both a string and action to preform (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.

Paths

4/31 Navigating the File System / home renault workspace

4/31 Navigating the File System /home/renault/workspace

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. Relative Path A path relative to the CWD. To move up:.. 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src Current Working Directory (CWD) Current location in the file system. Denoted by:. The directory from which the jvm was launched. Relative Path A path relative to the CWD. To move up:.. Absolute Path A path that starts at the root of the file system. Root: / 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? TopHat Question 3 Is /home/renault/workspace/cmdline an absolute or a relative path? 4/31

Navigating the File System /home/renault/workspace CS200Ex bin Data In Out src Palindrome bin src OrdinalEx bin src CmdLine bin src TopHat Question 2 Is./Palindrome/src an absolute or a relative path? TopHat Question 3 Is /home/renault/workspace/cmdline an absolute or a relative path? TopHat Question 4 If the CWD is /home/renault/workspace/cs200ex/bin, what is the relative path to In? 4/31

Exceptions

5/31 Exceptions What is an exception? Shorthand for an exceptional event. An event that interrupts the normal flow of the program.

5/31 Exceptions 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.

5/31 Exceptions 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.

5/31 Exceptions 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.

5/31 Exceptions 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.

6/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

7/31 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

8/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

9/31 Runtime Exception Causes Runtime Exceptions 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

10/31 Java Exception Hierarchy Object Throwable Error Exception... Runtime......

10/31 Java Exception Hierarchy Object Throwable Error Exception... Unchecked Runtime......

10/31 Java Exception Hierarchy Object Throwable Error Checked Exception... Unchecked Runtime......

11/31 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

11/31 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 Exceptions All other exceptions are checked exceptions. A method must handle all checked exceptions by either: Using a try-catch block, or Throwing the exception.

12/31 TopHat Question 5 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);

13/31 try-catch try { trystmt1 ;... trystmtn ; catch ( AnException e) { catchstmt1 ;... catchstmtn ;

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

14/31 TopHat Question 6 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.");

15/31 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.

15/31 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.

16/31 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().

17/31 Basic try-catch-finally try { trystatements ; catch ( AnException e) { catchstatements ; finally { finallystatements ;

17/31 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

18/31 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 + "."); catch ( InputMismatchException e) { System. out. print (" Catch."); finally { System. out. print (" Finally."); System. out. print (" Done.");

19/31 TopHat Question 8 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.");

20/31 Multiple catch try { trystatements ; catch ( Exception1 e) { catch1statements ; catch ( Exception2 e) { catch1statements ;... catch ( ExceptionN e) {

20/31 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

21/31 TopHat Question 9 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.");

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

22/31 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.

22/31 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.

22/31 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.

22/31 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.

22/31 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.

22/31 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?

22/31 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.

23/31 TopHat Question 11 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.");

24/31 Basic Throwing Exceptions Creating and Using Exceptions Constructors: Exception() Creates an Exception object. Exception(msg) Creates an Exception object containing the message msg.

24/31 Basic Throwing Exceptions Creating and Using Exceptions 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.

24/31 Basic Throwing Exceptions Creating and Using Exceptions 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 12 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."); 25/31

TopHat Question 13 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."); 26/31

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

27/31 Methods Throwing Exceptions Specifying Exceptions 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.

27/31 Methods Throwing Exceptions Specifying Exceptions 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

27/31 Methods Throwing Exceptions Specifying Exceptions 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.

28/31 TopHat Question 14 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 15 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 29/31

30/31 Further Reading COMP SCI 200: Programming I zybooks.com, 2015. zybook code: WISCCOMPSCI200Fall2017 Chapter 10. Exceptions

Appendix References Appendix

Appendix References References

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