Exception Handling Contents

Slides:



Advertisements
Similar presentations
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
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.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
COMP 121 Week 5: Exceptions and Exception Handling.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 Lecture 4 Exception Handling. 2 Exception-Handling Fundamentals An exception is an abnormal condition that arises in a code sequence at run time A Java.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Applets & Applications CSC 171 FALL 2001 LECTURE 15.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Example 1 :- Handling integer values public class Program1 { public static void main(String [] args) { int value1, value2, sum; value1 = Integer.parseInt(args[0]);
Java Software Solutions Foundations of Program Design Sixth Edition
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming: Guided Learning with Early Objects
Exceptions CSC 171 FALL 2004 LECTURE 24. READING Read Horstmann Chapter 14 This course covered Horstmann Chapters
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
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.
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Eighth Lecture Exception Handling in Java
Chapter 10 – Exception Handling
Objectives You should be able to describe: Interactive Keyboard Input
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
I/O Basics.
Creating and Modifying Text part 2
Chapter 14: Exception Handling
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
ATS Application Programming: Java Programming
Exceptions Exception handling is an important aspect of object-oriented design Chapter 10 focuses on the purpose of exceptions exception messages the.
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Exception Handling.
Web Design & Development Lecture 7
Chapter 12: Exceptions and Advanced File I/O
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
Exceptions 25-Apr-19.
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.
Exceptions 22-Apr-19.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Exceptions References: Jacquie Barker, Beginning Java Objects; Rick Mercer, Computing Fundamentals With Java; Wirfs-Brock et. al., Martin Fowler, OOPSLA.
Java Basics Exception Handling.
Exceptions 5-Jul-19.
CMSC 202 Exceptions 2nd Lecture.
Java Programming: From Problem Analysis to Program Design, 4e
Exceptions and Exception Handling
Java Exception Handling
Presentation transcript:

Exception Handling Contents Many classes in the Java standard library throw exceptions “throws clause” (or try-catch block) is needed in the function header of any function that contains a message to a library method that throws an exception Error message if “throws clause” or try-catch blocks are missing Types of exceptions Try-catch blocks The Exception hierarchy An example using try-catch blocks The anatomy of an exception

Exception Handling Most of Java’s I/O classes (and many others) throw exceptions. For example: Consider a function with a message readLine( ) directed to a BufferedInputReader object import java.io.*; //needed for streams and IOException public class ExceptionalExample { public static void main(String [ ] args) { throws IOException InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(“Enter a number”); String str = br.readLine( ); The statement “throws IOException” is required when using readLine( ). It must be included in the header of any function in which readLine( ) appears. Provide stream readers to convert characters (read as integers) into a string, then prompt the user for a number. Read the supplied number (as a String) from the keyboard.

Exception Handling If we fail to include the “throws IOException” clause in the main function header we will see the following error reported when we compile the program ExceptionalExample: c:\javacode>javac ExceptionalExample.java ExceptionalExample.java:10: unreported exception java.io.IOException; must be caught or declared to be thrown String str = readLine( ); 1 error c:\javacode> ^ Method readLine( ) throws an IOException. Any function that uses it must either throw the same exception (and pass the buck to the operating system to handle the exception) or catch the exception and provide its own error handling methodology. In the previous example we chose the first strategy.

Exception Handling Types of exceptions Checked exceptions – inability to acquire system resources (such as insufficient memory, file does not exist) Java checks at compile time that some mechanism is explicitly in place to receive and process an exception object that may be created during runtime due to one of these exceptions occurring. Unchecked exceptions – exceptions that occur because of the user entering bad data, or failing to enter data at all. Unchecked exceptions can be avoided by writing more robust code that protects against bad input values. Java does not check at compile time to ensure that there is a mechanism in place to handle such errors. It is often preferred to use Java’s exception handling capabilities to handle bad user input rather than trying to avoid such circumstances by providing user-input validation in the code.

Exception Handling The try / catch blocks try { //statements – one of which is capable of throwing an exception } catch (ExceptionTypeName objName) { //one or more statements to execute if this exception occurs } finally { //statements to be executed whether or not exception occurs } Encapsulate statement or statements that can throw an exception in a try block. One or more catch blocks must immediately follow a try block to provide error handling routines for any exceptions that occur while executing the statements in the try block. Each catch block specifies the type of exception that it handles in a parameter list. An optional finally block can be added at the end of the catch blocks to provide a set of statements that are always executed whether or not an exception occurs.

FileNotFoundException InterruptedIOException Exception Handling The exception hierarchy (partial) Exception RunTimeException DataFormatException IOException EOFException FileNotFoundException InterruptedIOException NumberFormatException All exceptions inherit from a base class Exception Common Exception sub classes include: IOException can be decomposed into specific classes of I/O errors NumberFormatException is a subclass of DataFormatException

Exception Handling Example Consider implementing the BufferReader readLine( ) example with try-catch clocks. import java.io.* public class ExceptionalExample { public static void main(String [ ] args) //no throws clause used here { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); System.out.println(“Enter a number”); try { String str = br.readLine( ); double num = Double.parseDouble(str); } try block encapsulates the readLine( ) method and the conversion from String to double. Will throw NumberFormatException if str cannot be converted to a double.

Exception Handling Example (continued) //add the catch blocks catch (IOException ioe) { //print a message to the screen System.out.println(ioe.toString( )); } catch (Exception e) { //catch any other exception and print a message to the screen System.out.println(e.toString( )); finally { System.exit(0); catch the IOException object thrown by readLine( ) Note! ioe is a handle (reference) to an IOException object thrown by readLine( ) Note! toString( ) is a method that all Classes inherit (implicitly). In the finally clause we ensure that the program terminates properly – exit(0) signifies normal termination. Since both catch blocks have the same implementation in this example, there is no need to single out IOException in a separate block.

Exception Handling The anatomy of an exception In the main( ) function of ExceptionalExample a BufferedReader object called br is created and attatcher to isr. An error occurs while attempting to read from the keyboard. An IOException object is created. br.readLine( ) is called inside of a try block in function main( ) ExceptionalExample The IOException is passed to the catch block in function main( ) Message is sent to object referenced by ioe to execute its toString( ) method (inherited from implicit base class Object) try { String str =br.readLine( ); } catch (IOException ioe){ System.out.println(ioe.toString()); } br:BufferedReader IOException new readLine( ) {..} toString( ) {…}