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.

Slides:



Advertisements
Similar presentations
Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Advertisements

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.
Errors and Exceptions The objectives of this chapter are: To understand the exception handling mechanism defined in Java To explain the difference between.
COMP 121 Week 5: Exceptions and Exception Handling.
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.
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.
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.
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.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
Exceptions and Exception Handling (2) Carl Alphonce CSE116.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
Exception Error handling. Exception 4 n An unusual occurrence during program execution that requires immediate handling n Errors are the most common type.
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.
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.
Object Oriented Programming
06 Exception Handling. 2 Contents What is an Exception? Exception-handling in Java Types of Exceptions Exception Hierarchy try-catch()-finally Statement.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
Slides Credit Umair Javed LUMS Web Application Development.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
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.
MCS 270 Spring 2014 Object-Oriented Software Development.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
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.
Java Programming: Exceptions1 Exceptions Reference: java.sun.com/docs/books/tutorial/essential/exceptions/
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
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.
Introduction to Exceptions in Java CS201, SW Development Methods.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
CS102 – Exceptions David Davenport Latest: May 2015
Advanced Programming Behnam Hatami Fall 2017.
ATS Application Programming: Java Programming
Exception Handling in Java
Web Design & Development Lecture 7
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

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 error handling from main business logic Based on ideas developed in Ada, Eiffel and C++ Java has a uniform approach for handling all synchronous errors  From very unusual (e.g. out of memory)  To more common ones your program should check itself (e.g. index out of bounds)  From Java run-time system errors (e.g., divide by zero)  To errors that programmers detect and raise deliberately

Throwing and catching An error can throw an exception throw ; By default, exceptions result in the thread terminating after printing an error message However, exception handlers can catch specified exceptions and recover from error catch ( e) { //statements that handle the exception }

Throwing an exception Example creates a subclass of Exception and throws an exception: class MyException extends Exception { } class MyClass { void oops() { if (/* no error occurred */) { /* normal processing */ } else { /* error occurred */ throw new MyException(); } } //oops }//class MyClass

Exceptional flow of control Exceptions break the normal flow of control. When an exception occurs, the statement that would normally execute next is not executed. What happens instead depends on: – whether the exception is caught, – where it is caught, – what statements are executed in the ‘catch block’, – and whether you have a ‘finally block’.

Approaches to handling an exception 1.Prevent the exception from happening 2.Catch it in the method in which it occurs, and either a.Fix up the problem and resume normal execution b.Rethrow it c.Throw a different exception 3.Declare that the method throws the exception 4.With 1. and 2.a. the caller never knows there was an error. 5.With 2.b., 2.c., and 3., if the caller does not handle the exception, the program will terminate and display a stack trace

Exception hierarchy Java organizes exceptions in inheritance tree: – Throwable – Error – Exception RuntimeException TooManyListenersException IOException AWTException

Java is strict Unlike C++, is quite strict about catching exceptions If it is a checked exception – (all except Error, RuntimeException and their subclasses), – Java compiler forces the caller must either catch it – or explicitly re-throw it with an exception specification. Why is this a good idea? By enforcing exception specifications from top to bottom, Java guarantees exception correctness at compile time. Here’s a method that ducks out of catching an exception by explicitly re-throwing it: void f() throws tooBig, tooSmall, divZero { – The caller of this method now must either catch these exceptions or rethrow them in its specification.

Error and RuntimeException Error – “unchecked”, thus need not be in ‘throws’ clause – Serious system problems (e.g. ThreadDeath, OutOfMemoryError) – It’s very unlikely that the program will be able to recover, so generally you should NOT catch these. RuntimeException – “unchecked”, thus need not be in ‘throws’ clause – Also can occur almost anywhere, e.g. ArithmeticException, NullPointerException, IndexOutOfBoundsException – Try to prevent them from happening in the first place! System will print stop program and print a trace

Catching an exception try { // statement that could throw an exception } catch ( e) { // statements that handle the exception } catch ( e) { //e higher in hierarchy // statements that handle the exception } finally { // release resources } //other statements At most one catch block executes finally block always executes once, whether there’s an error or not

Execution of try catch blocks For normal execution: – try block executes, then finally block executes, then other statements execute When an error is caught and the catch block throws an exception or returns: – try block is interrupted – catch block executes (until throw or return statement) – finally block executes When error is caught and catch block doesn’t throw an exception or return: – try block is interrupted – catch block executes – finally block executes – other statements execute When an error occurs that is not caught: – try block is interrupted – finally block executes

Example: try { p.a = 10; } catch (NullPointerException e) { System.out.println("p was null"); } catch (Exception e) { System.out.println("other error occurred"); } catch (Object obj) { System.out.println("Who threw that object?"); } finally { System.out.println(“final processing"); } System.out.println(“Continue with more statements");

Catch processing When an exception occurs, the nested try/catch statements are searched for a catch parameter matching the exception class A parameter is said to match the exception if it: – is the same class as the exception; or – is a superclass of the exception; or – if the parameter is an interface, the exception class implements the interface. The first try/catch statement that has a parameter that matches the exception has its catch statement executed. After the catch statement executes, execution resumes with the finally statement, then the statements after the try/catch statement.

Catch processing example print("now"); try { print("is "); throw new MyException(); print("a "); } catch(MyException e) { print("the "); } print("time\n"); Prints " now is the time ". Note that exceptions don't have to be used only for error handling Would it be a good idea to exceptions for non-error processing? But any other use is likely to result in code that's hard to understand.

Declaring an exception type Inherit from an existing exception type. Provide a default constructor and a constructor with one arg, type String. Both should call super(astring); Example: class MyThrowable extends Throwable { // checked exception MyThrowable () { super ("Generated MyThrowable"); } MyThrowable (String s) { super (s); } }

Declaring an exception type Inherit from an existing exception type. Provide a default constructor and a constructor with one arg, type String. Both should call super(astring); class ErrorThrower { public void errorMethod() throws MyThrowable { throw new MyThrowable ("ErrorThrower"); // forces this method to declare MyThrowable }

Exceptions are ubiquitous in Java Exception handling required for all read methods – Also many other system methods If you use one of Java's built in class methods and it throws an exception, you must catch it (i.e., surround it in a try/catch block) or rethrow it, or you will get a compile time error: char ch; try { ch = (char) System.in.read(); } catch (IOException e) { System.err.println(e); return;