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

Similar documents
Chapter 12 Exception Handling

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Java Errors and Exceptions. Because Murphy s Law never fails

BBM 102 Introduction to Programming II Spring Exceptions

C16b: Exception Handling

BBM 102 Introduction to Programming II Spring 2017

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

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

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 in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

COMP-202 Unit 9: Exceptions

COMP-202 Unit 9: Exceptions

CS159. Nathan Sprague

CSCI 1226 A Test #1. Wednesday, 10 October, 2018 Name: Student #: General Instructions Read and follow all directions carefully.

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

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

Chapter 15. Exception Handling. Chapter Goals. Error Handling. Error Handling. Throwing Exceptions. Throwing 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

Chapter 5. Exceptions. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

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

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

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

What are Exceptions?

Exceptions - Example. Exceptions - Example

ITI Introduction to Computing II

ITI Introduction to Computing II

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Correctness and Robustness

When we reach the line "z = x / y" the program crashes with the message:

Exception-Handling Overview

Lecture 19 Programming Exceptions CSE11 Fall 2013

Programming II (CS300)

For more details on SUN Certifications, visit

Lecture 4: Exceptions. I/O

ECE 122. Engineering Problem Solving with Java

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

Full file at Chapter 2 - Inheritance and Exception Handling

Programming II (CS300)

Comp 249 Programming Methodology Chapter 9 Exception Handling

Chapter 11 Handling Exceptions and Events. Chapter Objectives

Fundamentals of Object Oriented Programming

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Intro to Computer Science II. Exceptions

Exception Handling. Handling bad user input. Dr. Siobhán Drohan Maireád Meagher. Produced by:

CSC 1214: Object-Oriented Programming

Java Exception. Wang Yang

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

Exceptions and Error Handling

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

CP122 CS I. Chapter 11: File I/O and Exceptions

Exception Handling. Exception Handling

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

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

Lesson 3: Accepting User Input and Using Different Methods for Output

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

OBJECT ORIENTED PROGRAMMING. Course 6 Loredana STANCIU Room B616

Input-Output and Exception Handling

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

CSC Java Programming, Fall Java Data Types and Control Constructs

CSCI 261 Computer Science II

WOSO Source Code (Java)

Defensive Programming

Std 12 Lesson-10 Exception Handling in Java ( 1

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

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

More on Exception Handling

Typecasts and Dynamic Dispatch. Dynamic dispatch

Data Structures. 02 Exception Handling

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

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

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

Midterm Examination (MTA)

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

Introductory Programming Exceptions and I/O: sections

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

CP122 CS I. Chapter 11: File I/O and Exceptions

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Exceptions Handling Errors using Exceptions

Controls Structure for Repetition

Programming - 2. Common Errors

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

Lecture 8 " INPUT " Instructor: Craig Duckett

JAVA Ch. 4. Variables and Constants Lawrenceville Press

Happy Cinco de Mayo!!!!

9. Java Errors and Exceptions

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

CS 112 Introduction to Programming

Example Program. public class ComputeArea {

1. A company has vans to transport goods from factory to various shops. These vans fall into two categories: 50 items 150 items

C17: File I/O and Exception Handling

EXCEPTIONS. Fundamentals of Computer Science I

Building Java Programs

CS 3 Introduction to Software Engineering. 3: Exceptions

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

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

Checked and Unchecked Exceptions in Java

Transcription:

EXCEPTION HANDLING We do our best to ensure program correctness through a rigorous testing and debugging process, but that is not enough. To ensure reliability, we must anticipate conditions that could cause problems, and try to deal with them before the problems occur. In Java, we have exception handling, a powerful tool for ensuring program reliability. An error condition that occurs during program runtime is called an exception Exceptions are represented by exception objects, which are generated (thrown) in response to error conditions Java includes a rich set of routines for dealing with such circumstances: this is known as exception handling Java can do that either through: o Using try/catch blocks o Or if the code that could cause the exception is inside a method, then you can let that method throws an exception, and at the call block put the method s calling within try.. catch block. Catching exceptions through using try/catch block o Consists of try block followed by one or more catch blocks try block: encloses code that might throw an exception catch block(s) deal with any exception(s) thrown Syntax for try/catch block is as follows: // code that may throw an exception catch (ExceptionType parametername) { // code that handles an exception thrown in the try block o For catching exceptions: Statements in the try block are executed in sequence. When one of the statements throws an exception, control is passed to the matching catch block and statements inside the catch block are executed

Provided the catch block does not halt the program or return from the method, program execution continues at the first statement following the catch block If more than one exception is possible, multiple catch blocks can be written, but only one of them can be excused. If no error occurs then no exception is thrown, all statements in the try block are executed and the catch block(s) will be skipped Java Famous Exceptions: In Java Exception is a class with many descendants. o NullPointerException o ArrayIndexOutOfBoundsException o ClassCastException o RuntimeException o FileNotFoundException o ArithmeticException o IllegalArgumentException Why use an Exception? To tell the code using your method that something went wrong, so instead of showing the following message to the user o Exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 at RuntimeException.main(RuntimeException.java:8) o You can build the following message Accessed index 5, which isn t in the array The method that called it was main Debugging and understanding control flow Source: here.

Check the following example. EXCEPTION HANDLING EXAMPLE public class Quotient { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); We are expecting that we are dealing with smart user all the time and everything will be Ok. But that is not the case. Some weird cases could happen as follows: Imagine that the user input anything from the keyboard when s/he was asked to input the numbers. In this case you will have a run-time error and an exception called InputMismatchException will show up. Or imagine if the user input 0 as a second number. In this case you will have a run-time error and an exception called ArithmeticException will show up. Let s try to fix the problem above. public class QuotientWithIf { Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); if (number2!= 0) System.out.println(number1 + " / " + number2 + " is " + (number1 / number2)); else System.out.println("Divisor cannot be zero ");

Here we solved the problem of division by zero, but we did not fix the other problem. Let s try to fix the same problem by building a method to do the division. public class QuotientWithMethod { public static int quotient(int number1, int number2) { if (number2 == 0) { System.out.println("Divisor cannot be zero"); System.exit(1); return number1 / number2; Scanner input = new Scanner(System.in); // Prompt the user to enter two integers int number1 = input.nextint(); int number2 = input.nextint(); int result = quotient(number1, number2); System.out.println(number1 + " / " + number2 + " is " + result); Here we solved the problem of division by zero, but we did not fix the other problem. Another problem is, if the user makes any mistake we did not give him/her the chance to re-input the data again. So here is a solution for all that. Let s use the try catch to solve the previous problems. public class QuotientWithException { boolean G = true; while (G==true) { number1 = input.nextint(); number2 = input.nextint(); number3= number1 / number2;

System.out.println(number1 + "/"+ number2 +" = "+ number3); G= false; catch (ArithmeticException E) { System.out.println("you cant divide by zero"); catch (InputMismatchException W) { System.out.println("you have to input number"); if (input.hasnext()) input.next(); // while // main // class Let s use throws with try catch to solve the method problem public class QuotientWithException { public static int quotient (int number1, int number2) throws ArithmeticException { return number1 / number2; boolean G = true; while (G==true) { number1 = input.nextint(); number2 = input.nextint(); number3= number1 / number2; System.out.println(number1 + "/"+ number2 +" = "+ number3); G= false; catch (ArithmeticException E) { System.out.println("you cant divide by zero"); catch (InputMismatchException W) { System.out.println("you have to input number"); if (input.hasnext()) input.next(); // while // main // class

Here is another way to get data from user then validate this Data. Here we let the user input anything as a string, then we validate this string to see if it is an integer/float/.etc. or not. We use a wrapper class to validate that. Check the following code. int value; // number to be supplied by user String input; // value read from keyboard Scanner kb = new Scanner (System.in); System.out.print ("Enter a number: "); input = kb.nextline(); value = Integer.parseInt(input); catch (NumberFormatException e) { System.out.println (input + "is not valid.\n" +"Please enter digits only.");