Introduction to Exceptions in Java

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
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
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)
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.
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.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
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.
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]);
Preventing and Correcting Errors
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
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.
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 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.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
EXCEPTIONS There's an exception to every rule.. 2 Introduction: Methods  The signature of a method includes  access control modifier  return type 
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.
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.
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.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
Tirgul 13 Exceptions 1.
MIT AITI 2003 Lecture14 Exceptions
Chapter 13 Exception Handling
Introduction Exception handling Exception Handles errors
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
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.
Chapter 12 Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Exception Handling and Reading / Writing Files
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Java Exception Very slightly modified from K.P. Chow
Exceptions handling Try, catch blocks Throwing exceptions.
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.
Chapter 12 Exception Handling and Text IO Part 1
Exception Handling Contents
Exceptions.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exceptions.
Exception Handling.
Presentation transcript:

Introduction to Exceptions in Java

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 2

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 3

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

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”); … } 5

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. 6

Java Exceptions Examples of Java predefined exception classes (types): ArithmeticException IndexOutOfBoundsException IOException NullPointerException 7

Some Java Error and Exception Classes

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 9

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

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" gives name of exception, class and method, filename and line number where the exception occurred see ExceptionExample1.java. 11 11

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 12

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 13

Try block You can either 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

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

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

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 17

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 18

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

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 20

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 21

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 http://docs.oracle.com/javase/tutorial/essential/exc eptions/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<Integer> 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: " + } 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