Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.

Slides:



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

Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CS102--Object Oriented Programming
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
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.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Java Review 2 – Errors, Exceptions, Debugging Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
Java Software Solutions Foundations of Program Design Sixth Edition
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
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 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 9 : Exception Handling King Fahd University of Petroleum & Minerals College of Computer.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Object Oriented Programming
Program Errors Syntax errors Logic errors
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
COMP Exception Handling Yi Hong June 10, 2015.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Exception Handling Unit-6. Introduction An exception is a problem that arises during the execution of a program. An exception can occur for many different.
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Agenda Introduction Errors and Exception Exception Hierarchy Classification of Exceptions Built in Exceptions Exception Handling in Java User defined.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
Chapter 13 Exception Handling
Topic: Exception Handling
Introduction Exception handling Exception Handles errors
Chapter 12 Exception Handling
Exception Handling Chapter 9 Edited by JJ.
Managing Errors and Exceptions
Chapter 13 Exception Handling
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
CMSC 202 Exceptions.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department of Computer Science and Software Engineering

What is an Exception? Indication of problem during execution Examples – Divide by zero errors – Accessing the elements of an array outside its range – Invalid input – Opening a non-existent file – …

Exception Handling in Java3 Exceptions– a better error handling Exceptions act similar to method return flags in that encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java

Exception Example class DivByZero { public static void main(String args[]) { System.out.println(3/0); System.out.println(" Pls. print me. "); } Displays this error message Exception in thread "main" java.lang.ArithmeticException: / by zero at DivByZero.main(DivByZero.java:3) Causes the program to terminate

Another Example public class ExceptionExample { public static void main(String args[]) { String[] greek = {"Alpha","Beta"}; System.out.println(greek[2]); } Output: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at ExceptionExample.main(ExceptionExample.java:4)

Exception Handling in Java6 Coding Exceptions To handle the exception, you write a “try-catch” block. try { … normal program code } catch(Exception e) { … exception handling code } It prevents the program from automatically terminating

7 Example Output: Division by zero. After catch statement.

public class ExceptionExample { public static void main(String args[]) { try{ String[] greek = {"Alpha","Beta"}; System.out.println(greek[2]); } catch(Exception e) { System.out.print ("Index of array out of range"); }

Catching Multiple Exceptions Handle multiple possible exceptions by multiple successive catch blocks try { // code that might throw multiple exception } catch (IOException e) { // handle IOException and all subclasses } catch (ClassNotFoundException e2) { // handle ClassNotFoundException }

10 Exception Handler Exception "thrown" here Exception handler Thrown exception matched against first set of exception handlers If it fails to match, it is matched against next set of handlers, etc. If exception matches none of handlers, program is discarded

Exception Classes There are two kinds of exceptions in Java Predefined exception classes in the Java libraries New exception classes can be defined like any other class

Exception Classes from Standard Packages Predefined exception classes are included in the standard packages that come with Java ◦ For example: IOException NoSuchMethodException FileNotFoundException ◦ Many exception classes must be imported in order to use them import java.io.IOException; All predefined exception classes have the following properties: ◦ There is a constructor that takes a single argument of type String ◦ The class has an accessor method getMessage that can recover the string given as an argument to the constructor when the exception object was created.

Exception Classes from Standard Packages The predefined exception class Exception is the root class for all exceptions ◦ Every exception class is a derived class of the class Exception ◦ Although the Exception class can be used directly in a class or program, it is most often used to define a derived class ◦ The class Exception is in the java.lang package, and so requires no import statement 9-13

A Programmer-Defined Exception Class

15 Types of error: 1. Syntax errors: the rules of the language have not been followed (detected by the compiler). 2. Runtime errors occur while the program is running (detects an operation that is impossible to carry out). 3. Logic errors occur when a program doesn't perform the way it was intended to.

16 Runtime Errors

17 Catch Runtime Errors

18 Throwing Exceptions When the program detects an error, the program can create an instance of an exception type and throw it. This is known as throwing an exception.

19 Using the throws Clause Appears after method’s parameter list and before the method’s body Contains a comma-separated list of exceptions Exceptions can be thrown by statements in method’s body of by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses

20 Declaring, Throwing, and Catching Exceptions

21 Declaring Exceptions Every method state the types of checked exceptions it might throw. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

22 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

23 Sequence of Events for throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step

24 Sequence of Events for No throw Preceding step try block throw statement unmatched catch matching catch unmatched catch next step

25 throws clause specifies that method quotient may throw an ArithmeticException Repetition statement loops until try block completes successfully try block attempts to read input and perform division Retrieve input; InputMismatchExcept ion thrown if input not valid integers

26 Call method quotient, which may throw ArithmeticException If we have reached this point, input was valid and denominator was non-zero, so looping can stop Catching InputMismatchException (user has entered non-integer input) Read invalid input but do nothing with it Exception parameters Notify user of error made Catching ArithmeticException (user has entered zero for denominator) If line 32 was never successfully reached, loop continues and user can try again

27 The finally Clause try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } This block contains code that is ALWAYS executed, either after the “try” block code, or after the “catch” block code.

28 Sequence of Events for finally clause Preceding step try block throw statement unmatched catch matching catch unmatched catch next step finally

29 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements

30 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed

31 Trace a Program Execution try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed

32 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2

33 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.

34 Trace a Program Execution try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.