Exception Handling. Cheng, Wei COMP June 6, Title

Similar documents
D06 PROGRAMMING with JAVA

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

CS 111 Classes I 1. Software Organization View to this point:

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Using Files as Input/Output in Java 5.0 Applications

CS 121 Intro to Programming:Java - Lecture 11 Announcements

CS506 Web Design and Development Solved Online Quiz No. 01

What are exceptions? Bad things happen occasionally

Lecture J - Exceptions

public static void main(string args[]) { System.out.println( "f(0)=" + f(0));

JAVA - EXCEPTIONS. An exception can occur for many different reasons, below given are some scenarios where exception occurs.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Software Construction

Introduction to Java

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

public static void main(string[] args) { System.out.println("hello, world"); } }

Part I. Multiple Choice Questions (2 points each):

Building a Multi-Threaded Web Server

AP Computer Science Java Subset

AP Computer Science Java Mr. Clausen Program 9A, 9B

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Java Interview Questions and Answers

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Install Java Development Kit (JDK) 1.8

Chapter 2 Introduction to Java programming

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Java Programming Language

Basics of Java Programming Input and the Scanner class

Explain the relationship between a class and an object. Which is general and which is specific?

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Course Intro Instructor Intro Java Intro, Continued

Introduction to Programming

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

e ag u g an L g ter lvin v E ram Neal G g ro va P Ja

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

AP Computer Science File Input with Scanner

D06 PROGRAMMING with JAVA

Building Java Programs

Master of Sciences in Informatics Engineering Programming Paradigms 2005/2006. Final Examination. January 24 th, 2006

Object-Oriented Programming in Java

Simple Java I/O. Streams

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Java from a C perspective. Plan

Building Java Programs

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Smallest Java Package? Java.applet.* having 1 class and 3 interfaces. Applet Class and AppletContext, AppletStub, Audioclip interfaces.

Crash Course in Java

Homework/Program #5 Solutions

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Fundamentals of Java Programming

Third AP Edition. Object-Oriented Programming and Data Structures. Maria Litvin. Gary Litvin. Phillips Academy, Andover, Massachusetts

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

J a v a Quiz (Unit 3, Test 0 Practice)

WRITING DATA TO A BINARY FILE

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

I. INTRODUCTION. International Journal of Computer Science Trends and Technology (IJCST) Volume 3 Issue 2, Mar-Apr 2015

Introduction to Java. CS 3: Computer Programming in Java

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

13 File Output and Input

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Building Java Programs

Inside the Java Virtual Machine

Software Engineering Techniques

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

B.Sc (Honours) - Software Development

The following program is aiming to extract from a simple text file an analysis of the content such as:

The Interface Concept

Topic 11 Scanner object, conditional execution

Java Basics: Data Types, Variables, and Loops

Building Java Programs

Sample CSE8A midterm Multiple Choice (circle one)

6.1. Example: A Tip Calculator 6-1

C++ INTERVIEW QUESTIONS

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Remote Method Invocation

AP Computer Science Static Methods, Strings, User Input

1.00 Lecture 1. Course information Course staff (TA, instructor names on syllabus/faq): 2 instructors, 4 TAs, 2 Lab TAs, graders

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

The Sun Certified Associate for the Java Platform, Standard Edition, Exam Version 1.0

Java Crash Course Part I

CSE 8B Midterm Fall 2015

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

In this Chapter you ll learn:

Mail User Agent Project

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Application Development with TCP/IP. Brian S. Mitchell Drexel University

1. Properties of Transactions

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Grundlæggende Programmering IT-C, Forår Written exam in Introductory Programming

Comp 248 Introduction to Programming

Transcription:

Exception Handling Cheng, Wei COMP110-001 June 6, 2014 Title

Today Exception Handling Important in developing Java code. But not a major focus of this course This lecture: A lot of concepts Not much code

Recall Program 2 Program 2: A Simple Console Calculator Welcome to the simple console calculator! The following operations are supported: +, -, *, /, %. Enter your calculation separated by spaces: (Example: 2.5 + 3) 2.5 / 0 Division by 0 is not allowed If the user try to divide by 0, prints out a message

Recall Program 2 Program 2: A Simple Console Calculator Welcome to the simple console calculator! The following operations are supported: +, -, *, /, %. Enter your calculation separated by spaces: (Example: 2.5 + 3) 2.5 / 0 Division by 0 is not allowed Each of you used an if statement to test whether it is a division and the second operand is 0. If it is division by 0, did you still do the division after you print out the message?

Recall Program 2 If you choose not to do, you have handled this case by skipping the result calculation part If you still calculates the result, you will probably get an error like this: Exception in thread "main" java.lang.arithmeticexception: / by zero at Calculator.main(Calculator.java:XX) The program terminated due to the error.

What is the right thing to do When your code detects a problem? In program 2, we printed out a message to indicate a problem. And may choose to skip result calculation Not so much problem for a small program. We have control of everything involved. But things quickly become messy when we want to write something slightly bigger

What if. What if you are writing some classes for others to use What do you plan to do when your code detects some problem? Do you print out a message? What if the program that uses your class runs in graphical mode? Does the program really want some uncontrolled print-outs? Do you just let resulting errors terminate the program? Sounds like a terrible idea in most cases But if your class should do something and it is not performed properly, how to inform the program that uses the class? E.g., a method in your class is called and is supposed to return some value. When your code sees error, should it still return any value? If yes, what value?

What if. You are using someone s class for your program. E.g., you use the classes provided by Java to read from or write to a file. If some problems happens in reading / writing ( file not found, cannot read/write), how does your program get notified?

The need of a formal mechanism A formal mechanism is needed to handle problems Problems in one class should be reported and handled differently in different programs. This mechanism is different from return values in method-calling

Throw and Catch In Java, the mechanism is called Exception Handling Throw an exception: report a problem and asks for some code to handle it properly Catch an exception: a piece of code dedicated to handle one or more specific types of problem

Declaring, Throwing, and Catching Exceptions catch exception method1() { try { invoke method2; catch (Exception ex) { Process exception; method2() throws Exception { if (an error occurs) { throw new Exception(); declare exception throw exception Overview of Exception handling

Throwing Exceptions Example /** Set a new radius */ public void setradius(double newradius) throws IllegalArgumentException { if (newradius >= 0) radius = newradius; else throw new IllegalArgumentException( "Radius cannot be negative"); Step 1: add throws ExceptionType in method header Step 2: when problem occurs, throw new ExceptionType(. );

Catching Example 1 2 3 4 5 6 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. import java.util.scanner; 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);

Catching Example 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 { try { System.out.print("Enter an integer: "); int number = scanner.nextint(); // Display the result System.out.println( "The number entered is " + number); continueinput = false; catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); scanner.nextline(); // discard input while (continueinput);

The Java Exception Hierarchy ClassNotFoundException IOException ArithmeticException Exception AWTException NullPointerException RuntimeException IndexOutOfBoundsException Object Throwable Several more classes IllegalArgumentException LinkageError Several more classes Error VirtualMachineError AWTError Unchecked exception. Several more classes 15

Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions. 16

Unchecked Exceptions In most cases, unchecked exceptions reflect programming logic errors that are not recoverable. For example, a NullPointerException is thrown if you access an object through a reference variable before an object is assigned to it; an IndexOutOfBoundsException is thrown if you access an element in an array outside the bounds of the array. These are the logic errors that should be corrected in the program. Unchecked exceptions can occur anywhere in the program. To avoid cumbersome overuse of try-catch blocks, Java does not mandate you to write code to catch unchecked exceptions. 17

Let s see more examples with Checked Exceptions We want to use Java s FileInputStream class to read a file. So we do this: public void methodreadfile( String filename ) { FileInputStream fstream = new FileInputStream(filename); call fstream s method to read from file

Let s see more examples with Checked Exceptions The constructor can throw a checked exception So we have to handle it

Let s see more examples with Checked Exceptions So we revise our code to handle this exception: public void methodreadfile( String filename ) { try { FileInputStream fstream = new FileInputStream(filename); call fstream s method to read from file catch (FileNotFoundException e) { System.out.println( I cannot open the file + filename); System.out.println( This is the error message + e.getmessage() ); // do sth more meaningful here

Another Example public void calldivide() { Scanner s = new Scanner(System.in); try { int op1 = s.nextint(); int op2 = s.nextint(); System.out.println( divide( op1, op2 ) ); catch (BadNumberException e ) { System.out.println( e.getmessage() ); // do sth smart here

The finally Clause try { statements; catch(theexception ex) { handling ex; finally { finalstatements; 22

animation Trace a Program Execution try { statements; catch(theexception ex) { handling ex; finally { finalstatements; Next statement; Suppose no exceptions in the statements 23

animation Trace a Program Execution try { statements; catch(theexception ex) { handling ex; finally { finalstatements; The final block is always executed Next statement; 24

animation Trace a Program Execution try { statements; catch(theexception ex) { handling ex; finally { finalstatements; Next statement in the method is executed Next statement; 25

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; finally { finalstatements; Suppose an exception of type Exception1 is thrown in statement2 Next statement; 26

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; finally { finalstatements; The exception is handled. Next statement; 27

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; finally { finalstatements; The final block is always executed. Next statement; 28

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; finally { finalstatements; The next statement in the method is now executed. Next statement; 29

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; statement2 throws an exception of type Exception2. Next statement; 30

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Handling exception Next statement; 31

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Execute the final block Next statement; 32

animation Trace a Program Execution try { statement1; statement2; statement3; catch(exception1 ex) { handling ex; catch(exception2 ex) { handling ex; throw ex; finally { finalstatements; Rethrow the exception and control is transferred to the caller Next statement; 33

Extra Reading http://docs.oracle.com/javase/tutorial/essential/except ions/advantages.html

Next Class Read from / Write to Files