Fundamental Error Handling

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CS102--Object Oriented Programming
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Exception Handling Chapter 15 2 What You Will Learn Use try, throw, catch to watch for indicate exceptions handle How to process exceptions and failures.
COMP 121 Week 5: Exceptions and Exception Handling.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CPSC150 Click to edit Master title style Click to edit Master text styles Second level Third level Fourth level Fifth level 1 CPSC150 Exceptions When things.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
Exception Handling Recitation – 10/(23,24)/2008 CS 180 Department of Computer Science, Purdue University.
1 Lecture#8: EXCEPTION HANDLING Overview l What exceptions should be handled or thrown ? l The syntax of the try statement. l The semantics of the try.
Exception Handling (Chapter 8) CS 180 Recitation - February 29, 2008 Department of Computer Science Purdue University.
CS1101: Programming Methodology Aaron Tan.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lec.11 (Chapter 11) Exception Jiang (Jen) ZHENG July 13 th, 2005.
Chapter 14 – Exception Handling
Chapter 4 Assignment Statement
Lecture 14 Throwing Custom Exceptions
Exceptions: When things go wrong
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Chapter 5: Control Structures II
Chapter 3 Assignment Statement
Testing and Exceptions
The switch Statement The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression,
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Exceptions & exception handling
Phil Tayco Slide version 1.0 Created Nov. 26, 2017
ATS Application Programming: Java Programming
Exceptions & exception handling
Exceptions Problems in a Java program may cause exceptions or errors representing unusual or invalid processing. An exception is an object that defines.
Abdulmotaleb El Saddik University of Ottawa
Exception Handling.
Java Programming Arrays
Java Programming Loops
Part B – Structured Exception Handling
Java Programming Function Introduction
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exception Handling in Java
Java Programming Control Structures Part 1
Lecture 11 Objectives Learn what an exception is.
Java Programming Loops
CMSC 202 Exceptions 2nd Lecture.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Java Programming Function Introduction
Java Basics Exception Handling.
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Fundamental Error Handling Phil Tayco San Jose City College Slide version 1.1 Updated Nov. 5, 2018

Error Handling Consider the following. There are at least 2 potential run-time errors that can occur here: public static int findQuotient(int n, int d) { return n / d; } public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q);

Error Handling The input is expecting to look for integers in the input stream If the user enters alphabetic characters such as “six”, an “InputMismatchException” run time error will occur Also, if the user enters integers for n and d, but d is zero, a “ArithmeticException” run time error will occur These are events triggered by the user synchronously, meaning they can occur at specific lines of code being executed (“nextInt” or “n / d” for examples) As such, they can be handled with if statements in the code That works for the division by zero, but nextInt is a bit harder since that is code written for us by Java (the issue occurs within nextInt which we cannot see)

Error Handling An alternative viewpoint is to look at the areas where a run time error can occur: public static int findQuotient(int n, int d) { return n / d; } public static void main(String[] args) Scanner input = new Scanner(System.in); System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q);

Error Handling The lines of code in red are areas where these run time errors can occur. Java allows us to “wrap” this code This wrapping allows us to write code that says “here’s some code that may result in a run time error. If that happens, here’s how to handle it” try { System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); int q = findQuotient(n, d); System.out.println("Quotient is: " + q); }

Error Handling The “try” block wraps the code that tells Java there may be run time errors that can occur here. These errors are called “Exceptions” If an Exception occurs, an Exception object is generated and sent to another block of code after the “try” block called the “catch” block catch (InputMismatchException e) { System.out.println(“Input error. Please use only integers”); } The catch block is entered only if an Exception is generated within a try block

Error Handling Multiple catch blocks can be chained if the try block can generate multiple types of Exceptions catch (InputMismatchException e) { System.out.println(“Input error. Please use only integers”); } catch (ArithmeticException e) System.out.println(“Error with numbers”); The key to note here is that these are errors we have decided to handle. We are not putting these “in case the user enters bad data”, we are putting them to “ensure only handling integer data and denominators not equal to 0”

Error Handling Notice for the control flow that if an Exception is caught, code execution continues from there – it’s like a “go to” from the area in the try block where the Exception was found to the appropriate catch block where the Exception is caught Once the catch is done, normal program flow resumes after the catch blocks In this example, the effect is an error is handled, but the program ends from there As would normally be handled, keeping the program running if an Exception is found will involve using a loop – the key is putting the loop around the entire try…catch block

Error Handling do { try System.out.print("Enter numerator: "); int n = input.nextInt(); System.out.print("Enter denominator: "); int d = input.nextInt(); q = findQuotient(n, d); continueFlag = false; } catch (InputMismatchException e) System.out.println("Incorrect input error" ); input.nextLine(); catch (ArithmeticException e) System.out.println(e); } while (continueFlag == true); System.out.println("Quotient is: " + q);

Error Handling Here, the do…while loop surrounds the try…catch blocks controlling whether or not the process of collecting evaluating user data is correct The “continueFlag” variable (declared before the loop starts) manages the loop – the loop is set to continue until all the code in the try block is executed Notice in the InputMismatchException catch block, there’s an extra “nextLine()” function – this is due to input Scanner object still having a carriage return in its buffer that needs to be cleared so it can read the next line of input (a common issue with String input through the Scanner) Remember this does not mean the code is now foolproof – it only means we have code designed to capture Exceptions we designed to handle

The Exception Class The Exception class is actually a superclass in the Exception inheritance hierarchy “InputMismatchException” and “ArithmeticException” objects are types of Exceptions Because they inherit from Exception, it then allows for any catch block that the type of object thrown from a try block is also a type of Exception Put another way, this allows catch blocks to also use a sort of “default” way of catching Exceptions similar to the default case in a switch statement

Error Handling catch (InputMismatchException e) { System.out.println(“Input error. Please use only integers”); } catch (Exception e) System.out.println(“Exception: ” + e); Here, the last possible type of Exception that can be caught is the superclass Exception object Any type of Exception that gets thrown in a try block now has a “default” catch block if any of the other catch blocks do not catch the type thrown In this example, if an unforeseen Exception such as “RunTimeException” is thrown, the last catch block will catch it polymorphically

The Exception Class The default catch Exception block is useful in case an unforeseen Exception is thrown As good practice, since you are already setting up the code infrastructure to do a try…catch set, it is helpful to have a last catch block for the generic Exception class as a last resort try…catch should still be used to identify catching known Exceptions. Default Exceptions are best used for backup purposes

Summary The text goes into more detailed extent on the use of try…catch as well as another clause, “finally” Exceptions are also classes so it is possible to define your own Exception subclasses Methods can also be designed to “throws” specific Exceptions Best practice is to try and define through requirements what types of issues you want your program to handle and use code (try…catch or if…else statements) to address them try…catch is nice because it can structurally handle multiple potential issues in a set of code Use exception handling as often as possible but only do so as required for as much as one can foresee