Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Topics Introduction Types of Errors Exceptions Exception Handling
Yoshi
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
COMP 121 Week 5: Exceptions and Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
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.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
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.
Handling Errors with Exception (in Java) Project 10 CSC 420.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
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.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
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.
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.
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.
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.
Slides Credit Umair Javed LUMS Web Application Development.
Chapter 9: Exceptions For error/problem situations Exception classes –ArithmeticException, IOException, etc. –checked exceptions try blocks –catch statements.
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.
Practice Session 9 Exchanger CyclicBarrier Exceptions.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
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.
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.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
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.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Exceptions 10-Nov-18.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Introduction to Exceptions in Java

2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions –Exceptions can be handled in some way Example: division by zero –Errors are unrecoverable situations Example: running out of memory

3 Exceptions Exception : an abnormal or erroneous situation at runtime Examples: Division by zero Array index out of bounds Illegal input number format Following a null reference

4 Exceptions These erroneous situations throw an exception Exceptions can be thrown by the runtime environment or by the program itself

5 Throwing Exceptions You have seen a situation where a program throws an exception Example in ArrayStack.java: public T pop() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException(“Stack”); … }

6 Java Exceptions In Java, an exception is an object There are predefined exception classes in the Java API Exception Its subclass RuntimeException Its subclass NullPointerException etc.

7 Java Exceptions Examples of Java predefined exception classes (types): IllegalArgumentException ArrayIndexOutOfBoundsException IOException NullPointerException

8 Some Java Error and Exception Classes

9 Java Exceptions We can throw an exception object of one of these predefined types, or we can define our own exception classes How? We can extend Exception or one of its subclasses

10 Example from ArrayStack public class EmptyCollectionException extends RuntimeException { /** * Sets up this exception with an appropriate message. collection String representing name of collection */ public EmptyCollectionException (String collection) { super (“The ” + collection + “ is empty.”); }

11 Uncaught Exceptions If an exception is not handled at all by the program, a standard error message is printed by the Java runtime system and the program is terminated Example: java.lang.ArrayIndexOutOfBoundsException: 5 at ExceptionExample1.main(ExceptionExample1.java:17) Exception in thread "main"

12 Catching Exceptions To handle an exception in your program: –A method, or the runtime environment, that detected an error during execution throws an exception –The code that deals with the exception is said to catch or handle it

13 How to Catch an Exception Syntax of try-catch statement : try { // try block: statements(s) that might cause an exception to // be thrown } catch ( possible-exception-type e) { // catch clause: statements to handle the problem, // referring to the exception object e }

Try block You can put each line of code that might throw an exception within its own try block and provide separate exception handlers for each, or put all the code within a single try block and associate multiple handlers with it. 14

15 Catching Exceptions: Example public static void main (String[] args) throws Exception { BufferedReader keyboard = new BufferedReader (new InputStreamReader(System.in), 1); System.out.print("Enter an integer:"); String userTyped = keyboard.readLine(); //continued

16 Catching Exceptions: Example try { int value = Integer.parseInt(userTyped); } catch (NumberFormatException e) { System.out.println("Hey, " + e.getMessage() + " is not an integer!"); }

17 Catching Exceptions How try-catch works: –When the try-catch statement is executed, the statements in the try block are executed –If no exception is thrown: Processing continues with the statement following the try-catch statement –If an exception is thrown: Control is immediately passed to the first catch clause whose specified exception corresponds to the class of the exception that was thrown

18 Catching Exceptions:Example Example: try to create a file (in a non-existent directory) String filename = "/nosuchdir/myfilename“ ; try { new File(filename).createNewFile() ; } catch (IOException e) { System.out.println("Unable to create" + filename + ":" + e.getMessage()) ; } // execution continues here * code from Java Developers Almanac

19 Catching Exceptions: Example Here is the output : Unable to create /nosuchdir/myfilename: The system cannot find the path specified

20 Catching Exceptions If an exception is not caught and handled where it occurs: –Control is immediately returned to the method that invoked the method that produced the exception –If that method does not handle the exception (via a try statement with an appropriate catch clause) then control returns to the method that called it This process is called propagating the exception

21 Catching Exceptions Exception propagation continues until – The exception is caught and handled – Or until it is propagated out of the main method, resulting in the termination of the program

Catch Blocks A single catch block can handle more than one type of exception. This can reduce code duplication and lessen the temptation to catch an overly broad exception. In the catch clause, specify the types of exceptions that the block can handle and separate each exception type with a vertical bar (|). 22

A Try-Catch-Finally Example The try-catch-finally syntax: try { code } catch(exception1) {statements} catch(exception2) {statements} catch(exception3|exception4){statements} … finally {statements} 23

Try example As an example [see al/exceptions/try.html], consider exception handling for a writeList method using a ListOfNumbers class. We enclose the exception-throwing statements of the writeList method within a try block. 24

Try example, continued private List list; private static final int SIZE = 10; PrintWriter out = null; try { System.out.println("Entered try statement"); out = new PrintWriter(new FileWriter("OutFile.txt")); for (int i = 0; i < SIZE; i++) System.out.println("Value at: " + i + " = " + list.get(i)); } 25

Try example continued If an exception occurs within the try block, that exception is handled by an exception handler associated with it. To associate an exception handler with a try block, you must put a catch block after it. 26

Catch Block Two exception handlers for the writeList method: one for the two checked exceptions that can be thrown within the try statement: catch(FileNotFoundException e) { System.err.println("FileNotFoundException: " + e.getMessage()); // Ask for new filename throw new SampleException(e); } catch(IOException e) { System.err.println("Caught IOException: " + e.getMessage()); } 27

Catch Block Both handlers print error messages. The first handler throws a user-defined exception. You might want to do this if you want your program to handle an exception in this situation in a specific way (exception handlers can do more than just print error messages or halt the program). 28

Finally Block The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. Useful for more than just exception handling: it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. 29

Finally Block The try block of the writeList method that we have been using opens a PrintWriter. The program should close that stream before exiting the writeList method. writeList's try block can exit in one of the following ways: (1)The new FileWriter statement fails and throws an IOException. (2) An FileNotFoundException is thrown (3) The list.get(i) statement fails and throws an ArrayIndexOutOfBoundsException (4) Everything succeeds and the try block exits normally. 30

Finally Block The runtime system always executes the statements within the finally block, so it's the perfect place to perform cleanup. The following finally block for the writeList method cleans up and then closes the PrintWriter. finally { if (out != null) { System.out.println("Closing PrintWriter"); out.close(); } else System.out.println("PrintWriter already closed"); } 31