06 - Exceptions. 2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr.

Slides:



Advertisements
Similar presentations
Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
Advertisements

Exceptions Ensuring program reliability. Program correctness The term program correctness refers to a program’s working as advertised; that is, it produces.
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
For use of Cleveland State's IST410 Students only 1 Exception.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
Exception Handling Topics We will discuss the following main topics: – Handling Exceptions – Throwing Exceptions – More about Input/Output Streams.
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.
11-Jun-15 Exceptions. 2 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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. COMPSCI 125 Spring 2005 Chapter 8  Errors and Exceptions Throwable class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
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
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
Preventing and Correcting Errors
Exception Handling. Exceptions and Errors When a problem encounters and unexpected termination or fault, it is called an exception When we try and divide.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
Chapter 12: Exception Handling
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Slides Credit Umair Javed LUMS Web Application Development.
Java I/O Java I/O is based on input streams and output streams. All input and output are defined in the Java IO package. 1.
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.
BIO Java 1 Exception Handling Aborting program not always a good idea – can’t lose messages – E-commerce: must ensure correct handling of private.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exceptions in Java. What is an exception? An exception is an error condition that changes the normal flow of control in a program Exceptions in Java separates.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
MIT AITI 2004 – Lecture 14 Exceptions Handling Errors with Exceptions.
Copyright © Curt Hill Error Handling in Java Throwing and catching 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:
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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:
Introduction to Exceptions in Java CS201, SW Development Methods.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Geoff Holmes Week 5 problems Handling Throwing Catching Multiple exceptions Finally clause Examples Exception Handling.
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Introduction Exception handling Exception Handles errors
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Exception Handling Chapter 9.
Java Programming Language
Exception Handling Chapter 9 Edited by JJ.
Exception Handling in Java
Exceptions 10-May-19.
Exception Handling.
Presentation transcript:

06 - Exceptions

2 ©S. Uchitel, 2004 A familiar sight? Bluescreen.scr

3 ©S. Uchitel, 2004 … and some more

4 ©S. Uchitel, 2004 … and even more

5 ©S. Uchitel, 2004 Exceptions Things go wrong! It's a fact of life! Things go wrong! It's a fact of life! Successful compilation does not guarantee correct behaviour Successful compilation does not guarantee correct behaviour  Incorrect downcast of an object  Access to a method or field on a null reference.  A class not present in the classpath As a user of a particular class or method you must prepare to deal with exceptions. As a user of a particular class or method you must prepare to deal with exceptions. As a designer you need to anticipate wrong parameters and errors. As a designer you need to anticipate wrong parameters and errors. The underlying principle is to deal with failures or exceptional circumstances gracefully. The underlying principle is to deal with failures or exceptional circumstances gracefully.

6 ©S. Uchitel, 2004 Exceptions: The user’s perspective Method register may terminate... Method register may terminate... ... normally returning a boolean value, or ... abnormally throwing an exception of type StudentUnknown If we want to use the method we must either... If we want to use the method we must either...  deal with the exception, or  declare that our method may propagate the exception upwards public boolean register(Student s, Option o) throws UnknownStudent { //throws exception when Student s is not an IC student //returns false when the student is not registered because the option // is full // is full... //Here goes the code, but as user’s we are not interested......}

7 ©S. Uchitel, 2004 Dealing with exceptions public Collection massRegistration(Collection c, Option o) { //Registers students in c, on option o. //Registers students in c, on option o. //Returns students for which registration was unsuccessful //Returns students for which registration was unsuccessful Collection failed = new HashSet(); Collection failed = new HashSet(); Iterator i = c.iterator(); Iterator i = c.iterator(); while (i.hasNext()) { while (i.hasNext()) { Student s = (Student) i.next(); Student s = (Student) i.next(); try { try { if (!register(s, o)) if (!register(s, o)) failed.add(s); failed.add(s); } catch (UnknownStudent e) { catch (UnknownStudent e) { failed.add(s); failed.add(s); } } return failed; return failed;} try this block of code and if any method within it raises an exception go to the catch block if a StudentUnknown exception has happened, execute this block of code

8 ©S. Uchitel, 2004 Propagating Exceptions public Collection massRegistration(Collection c, Option o) throws UnknownStudent { //Registers students in c, on option o. //Registers students in c, on option o. //Returns students for which registration was unsuccessful //Returns students for which registration was unsuccessful //Throws exception when if student in c is not an IC student //Throws exception when if student in c is not an IC student Collection failed = new HashSet(); Collection failed = new HashSet(); Iterator i = c.iterator(); Iterator i = c.iterator(); while (i.hasNext()) { while (i.hasNext()) { Student s = (Student) i.next(); Student s = (Student) i.next(); if (!register(s, o)) if (!register(s, o)) failed.add(s); failed.add(s); } return failed; return failed;} This method does not deal with the exception that register may throw. If register throws an exception, massRegistration will stop and propagate it to its own caller.

9 ©S. Uchitel, 2004 Dealing with multiple exceptions Assume: Assume: boolean writeToFile(String s, String content) throws Exception boolean writeToFile(String s, String content) throws Exception public void writeToFile(String content) throws Exception { String fileName; String fileName; boolean success = false; while (!success) { System.out.println("Type in a file name."); fileName = InputReader.readString(); try { success = writeToFile(fileName, content); success = writeToFile(fileName, content); } catch (FileExists e) { catch (FileExists e) { System.out.println("File already exists!"); System.out.println("File already exists!"); } catch (InvalidFileName e) { catch (InvalidFileName e) { System.out.println("File name is invalid!"); } }} Deals with only two subclasses of exception, hence must declare that it may raise other exceptions

10 ©S. Uchitel, 2004 Exceptions: Java syntax summary // For the provider of the method returnType methodName(/* arguments */) throws {…} = exceptiontype, exceptiontype, … = exceptiontype, exceptiontype, … // when calling a method try { // call the method } catch (ExceptionType name) { … } // any number of catch clauses catch (ExceptionType name) { … } finally { /* code here always gets executed regardless */ }

11 ©S. Uchitel, 2004 Exceptions Are Objects Too Like objects exceptions have a type and are instantiated with new. Like objects exceptions have a type and are instantiated with new. Exceptions can be defined with custom structure, operations, constructors, etc. by extending any pre-defined exception type. Exceptions can be defined with custom structure, operations, constructors, etc. by extending any pre-defined exception type. The Exception class is the parent class of all exception classes. The Exception class is the parent class of all exception classes.  Exception();  Exception(String s); // s should be an informational message  getMessage(); // displays informational message  printStackTrace(); //prints to standard error output the stack //of method calls //of method calls

12 ©S. Uchitel, 2004 Throwing Exceptions Throwing exceptions is easy. Use the throw keyword Throwing exceptions is easy. Use the throw keyword public boolean register(Student s, Option o) throws UnknownStudent { //throws exception when Student s is not an IC student //returns false when the student is not registered because the option... if (! IC.students.conatins(s)) throw new UnknownStudent(); else... //Check if option o is full }

13 ©S. Uchitel, 2004 Using the Exception methods public class ExceptionExample { public static void main(String[] args) { public static void main(String[] args) { try { exceptionThrower(); exceptionThrower();} catch (Exception e) { System.out.println(“Found an exception, this is what it said:”); System.out.println(“Found an exception, this is what it said:”); System.out.println(e.getMessage()); System.out.println(e.getMessage()); System.out.println(“Stack at the time when it was thrown:”); System.out.println(“Stack at the time when it was thrown:”); e.printStackTrace(); e.printStackTrace();} } static private void exceptionThrower() throws Exception { static private void exceptionThrower() throws Exception { throw new Exception(“Hello!”); }} Output?

14 ©S. Uchitel, 2004 Writing Exception classes This class extends Exception and overrides the getMessage method. This class extends Exception and overrides the getMessage method. public class InvalidFileName extends Exception { public String getMessage() { return "InvalidFileName message (" + super.getMessage()+ ")"; }}

15 ©S. Uchitel, 2004 Java Exception Class Hierarchy Object Throwable Exception IOException IndexOutOfBoundsException NoSuchMethodException RuntimeException User can Define FileNotFoundException User Can Define ClassCastException Error all subclasses of Runtime are unchecked all subclasses of Runtime are unchecked all other subclasses of Exception are checked

16 ©S. Uchitel, 2004 The Error throwable class! These represent serious errors, exceptions that applications should not try to catch, e.g., error in the JVM. These represent serious errors, exceptions that applications should not try to catch, e.g., error in the JVM. Rarely used. Mostly to terminate programs with customized failure modes. Rarely used. Mostly to terminate programs with customized failure modes.

17 ©S. Uchitel, 2004 Checked and unchecked exceptions Checked exceptions – Declared explicitly in the method signature. The compiler will verify that the exception is either caught or thrown by all calling methods. Checked exceptions – Declared explicitly in the method signature. The compiler will verify that the exception is either caught or thrown by all calling methods. Unchecked exceptions (extend RuntimeException) Unchecked exceptions (extend RuntimeException)  Do not need to be declared in the signature of the method that throws them.  Automatically propagated to the calling context if not caught.  Cause program termination if not caught.

18 ©S. Uchitel, 2004 Exceptions: Summary (1) Primary means for defensive programming. Primary means for defensive programming.  Support robust code.  Allow to anticipate the unexpected. Exceptions are thrown by the called method. Exceptions are thrown by the called method. Exception types are declared in the method signature Exception types are declared in the method signature Every exceptions must be either Every exceptions must be either  caught by the calling method and dealt with, or  delcared and propagated to the caller of the calling method. Exceptions are objects, instances of classes. Exceptions are objects, instances of classes.

19 ©S. Uchitel, 2004 Exceptions: Summary (2) Catching Exceptions Catching Exceptions  Done according to the exception type  Any number of catch clauses can be specified.  The order in which the catch clauses are matched is the sequential ordering in the java source file.  A catch clause for a supertype will catch all its exception subtypes e.g. catch (Exception e) {…} catches all exceptions  The catch clause for most specific exceptions must be placed before the more general ones.