Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.

Slides:



Advertisements
Similar presentations
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Index Exception handling Exception In Java Exception Types
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
Java Programming Exceptions. Java has a built in mechanism for error handling and trapping errors Usually this means dealing with abnormal events or code.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Exception Handling. Introduction An exception is an abnormal condition that arises in a code sequence at run time. In computer languages that do not support.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Introduction to Java Chapter 11 Error Handling. Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
CS203 Java Object Oriented Programming Errors and Exception Handling.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Chapter 11 Exception Handling F Exceptions and Exception Types F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Object Oriented Programming
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Object Oriented Programming with Java (150704).  Throwable Exception (This class will catch exceptions generated by prog.) (Create your own custom exception.
COMP Exception Handling Yi Hong June 10, 2015.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
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.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Chapter 13 Exception Handling
Chapter 10 – Exception Handling
Chapter 13 Exception Handling
Topic: Exception Handling
Introduction to Exceptions in Java
Chapter 12 Exception Handling and Text IO
Exceptions 10-Nov-18.
Chapter 12 Exception Handling
Chapter 13 Exception Handling
Exception Handling in Java
Chapter 13 Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Presentation transcript:

Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions When Using Exceptions F Exception Types

Mistakes happen No matter how well designed a program is, there is always the chance that some kind of error will arise during its execution. F Attempting to divide by 0; F Attempting to read from a file which does not exist; F Referring to non-existing item in array; F etc. exception An exception is an event that occurs during the execution of a program that disrupt its normal course.

Main idea F Java was designed with the understanding that errors occur, that unexpected events happened and the programmer should always be prepared for the worst. F The preferred way of handling such conditions is to use exception handling, an approach that separates a program’s normal code from its error-handling code.

Example: Open file and read contents ask the user for the name of a file open the file read the contents do something with the contents close the file Does the file exist? Can we open the file? Can we read data from the file?

Exceptions F Exception is a useful programming construct because the location where an error is detected is usually not the place where the appropriate solution is known.  Constructors are not permitted to return a null value, furthermore there might be multiple reasons for a failure.  Does a null value returned by a file open operation mean the file does not exist, or that it exists but cannot be read? Finally, what if a null value is perfectly legal?

Claiming, Throwing, and Catching Exceptions

Example 1a: Division F When a statement causes error, the method containing the statement creates exception object and passes it to the system. Class Test { public static main(String args[]) { int d, a; d = 0; a = 1/d; } Output: java.lang.ArithmeticException: / by zero at samples.Test.main(Test.java:5)

Exception handling F After a method throws an exception, the Java runtime system begins the process of finding the code to handle the error. F The code that handles the error is called the exception handler; it is found by searching backward through a chain of method calls, starting from the current method. F The process of finding a handler is called catching an exception. F If no handler is found, the program terminates.

Example 1b: Division int d, a; d = 0; try { a = 1/d; System.out.println(“It will not be printed”); } catch (ArithmeticException except) { System.out.println(“Division by zero!”); } System.out.println(“After catch statement.”); Output: Division by zero! After catch statement.

Example 1c: Division int d, a; d = 0; try { // The method now claims an exception and throws it if the divisor is zero. if(d==0) throw new RuntimeException(); a = 1/d; } catch (RuntimeException except) { System.out.println(except); } System.out.println(“After catch statement.”); Output: java.lang.RunTimeException After catch statement.

Example 2: String to integer String str1=“123”, str2=“xwz”; try { int i1 = Integer.parseInt(str1); System.out.println(“The 1st int value ” + i1); int i2 = Integer.parseInt(str2); System.out.println(“The 2nd int value ” + i2); } catch (NumberFormatException exc) { System.out.println(exc); } … Output The 1st int value is 123 java.lang.NumberFormatException: For input string: "xwz"

Exceptions handling 1. Claiming Exceptions 2. Throwing Exceptions 3. Catching Exceptions

1. Claiming Exceptions throws To claim an exception in a method, use the throws keyword. modifiers MethodName(list of params) throws Exception_1, Exception_2,..., Exception_N Example: public void myMethod() throws IOException {... }

Claiming Exception Example // The method divide(k,m) returns result of division, // n = k/m; throws public int divide(int k, int m) throws RuntimeException RuntimeException {... }

2. Throwing Exceptions In the method that has claimed the exception, you can throw an object of the exception if the exception arises. throw new TheException(); TheException e = new TheException(); throw e;

Throwing Exceptions Example public int divide(int k, int m) throws RunTimeException { if(m == 0) { throw new RuntimeException(”Divisor can’t be zero"); } return k/m; }

3. Catching Exceptions try { statements; } catch(Exception1 e){ handler for exception1; handler for exception1;} catch (Exception2 e) { handler for exception2; handler for exception2;}... catch (ExceptionN e){ handler for exceptionN; handler for exceptionN;}

Catching Exceptions Example try { int n = divide(k,m); } catch(RuntimeException e){ System.out.println(“Error! Division by 0.”); }

Methods of Exception object F public String getMessage() // Returns detailed message of the object F public String toString() // Returns short description of the object F public void printStackTrace() // Print trace information: class name, method name, file name, and line number. java.lang.ArithmeticException: /by zero at MyClass,divide(MyClass.java:5)

Open File Example, cont. try try { File fd = new File(filename); processFile(fd); fd.close() } catch (FileNotFound e) { System.out.println(“Cannot find file”+e); System.out.println(“Cannot find file”+e); e.printStackTrace(); e.printStackTrace();} catch (FileOpenFailed e) { System.out.println(“Cannot open file”+e); System.out.println(“Cannot open file”+e); e.printStackTrace(); e.printStackTrace();}

Claiming, Throwing, and Catching Exceptions

Re Rethrowing Exceptions try { statements; } catch(TheException e) { perform operations before exits; throw e; }

Catching Exceptions

The finally Clause F You may want some code to be executed regardless of whether an exception occurs or is caught. Java has a finally clause that can accomplish this objective. try { statements; } catch(TheException1 e) { handling e; } catch(TheException2 e) { handling e; } finally { finalStatements; }

The finally Clause  If no exception arises in the try block, finalStatement is executed.  If one of the statements causes an exception in try block that is caught in a catch clause, the other statements in try block are skipped, the catch clause is executed, and the finally clause is executed. * If the catch clause does not rethrow an exception, the next statement is executed. * If it does, the exception is passed to the caller of the method.  If one of the statements causes an exception is not caught in any catch clause, the other statements in the try block are skipped, the finally clause is executed, and the exception is passed to the caller of this method.

Example: finally Suppose that statement2 causes an exception ex2 : try { statement1; statement2; statement3; } catch(TheException1 ex1) { handling ex1; } catch(TheException2 ex2) { handling ex2; } finally { finalStatement; } statement 4; Output: statement1; finalStatement; statement4;

Cautions When Using Exceptions F Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. F Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

Exceptions and Exception Types