Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.

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

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Topics Introduction Types of Errors Exceptions Exception Handling
Exceptions Chapter Throwing and Catching Exceptions When a program runs into a problem that it cannot handle, it throws an exception. Exceptions.
Exception Handling. Background In a perfect world, users would never enter data in the wrong form, files they choose to open would always exist, and code.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
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.
Exception Handling Yaodong Bi Exception Handling Java exception handling Try blocks Throwing and re-throwing an exception Catching an.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Objectives Understanding what an exception is Understanding the heirarchy of exception classes Learn the types of exception and how to catch and handle.
Java Exceptions, Cloning, Serialization Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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 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. 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.
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.
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.
Java Programming Exceptions Handling. Topics: Learn about exceptions Try code and catch Exceptions Use the Exception getMessage() method Throw and catch.
CIS 270—Application Development II Chapter 13—Exception Handling.
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.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
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.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
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 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.
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.
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.
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….
Introduction to Exceptions in Java
Introduction to OO Program Design
CS102 – Exceptions David Davenport Latest: May 2015
Chapter 12 Exception Handling
Web Design & Development Lecture 7
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Exception Handling.
Presentation transcript:

Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park

Overview Background Errors Exceptions Java support Representing exceptions Generating & handling exceptions Designing & using exceptions

Program Errors Syntax (compiler) errors Errors in code construction (grammar, types) Detected during compilation Run-time errors Operations illegal / impossible to execute Detected during program execution Treated as exceptions in Java Logic errors Operations leading to incorrect program state May (or may not) lead to run-time errors Detect by debugging code

Exceptions Rare event outside normal behavior of code Examples Division by zero Access past end of array Out of memory Number input in wrong format (float vs. integer) Unable to write output to file Missing input file

Exception Handling Performing action in response to exception Examples Exit program (abort) Ignore exception Deal with exception and continue Print error message Request new data Retry action

Exception Handling – Problem May not be able to handle exception locally Not enough information in method / class Need more information to decide action Handle exception in calling function(s) instead Decide at application level (instead of library) Examples Incorrect data format  ask user to reenter data Unable to open file  ask user for new filename Insufficient disk space  ask user to delete files Will need to propagate exception to caller(s)

Exception Handling – Exit Program Approach Exit program with error message / error code Example if (error) { System.err.println(“Error found”);// message System.exit(1);// error code } Problem Drastic solution Event must be handled by user invoking program Program may be able to deal with some exceptions

Exception Handling – Error Code Approach Exit function with return value  error code Example A( ) { if (error) return (-1); } B( ) { if ((retval = A( )) == -1) return (-1); } Problems Calling function must check & process error code May forget to handle error code May need to return error code to caller Agreement needed on meaning of error code Error handling code mixed with normal code

Exception Handling – Throw Exception Approach Throw exception Example A( ) { if (error) throw new ExceptionType(); } B( ) { try { A( ); } catch (ExceptionType e) {...action... } } Java exception backtracks to caller(s) until matching catch block found

Exception Handling – Throw Exception Advantages Compiler ensures exceptions are caught eventually No need to explicitly propagate exception to caller Backtrack to caller(s) automatically Class hierarchy defines meaning of exceptions No need for separate definition of error codes Exception handling code separate & clearly marked

Representing Exceptions Exceptions represented as Objects derived from class Throwable Code public class Throwable( ) extends Object { Throwable( )// No error message Throwable( String mesg )// Error message String getMessage()// Return error mesg void printStackTrace( ) { … }// Record methods …// called & location }

Representing Exceptions Java Exception class hierarchy Two types of exceptions  checked & unchecked

Object Error Throwable Exception LinkageError VirtualMachoneError ClassNotFoundException CloneNotSupportedException IOException AWTError … AWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException … Representing Exceptions Java Exception class hierarchy

Exceptions – Examples FileNotFoundException ( java.io ) Request to open file fails IllegalArgumentException ( java.lang ) Method passed illegal / inappropriate argument IOException ( java.io ) Generic I/O error NullPointerException ( java.lang ) Attend to access object using null reference UnsupportedOperationException ( java.lang ) Object does not provide requested operation

Unchecked Exceptions Class Error & RunTimeException Serious errors not handled by typical program Usually indicate logic errors Example NullPointerException, IndexOutOfBoundsException Catching unchecked exceptions is optional Handled by Java Virtual Machine if not caught

Checked Exceptions Class Exception (except RunTimeException) Errors typical program should handle Used for operations prone to error Example IOException, ClassNotFoundException Compiler requires “catch or declare” Catch and handle exception in method, OR Declare method can throw exception, force calling function to catch or declare exception in turn Example void A( ) throws ExceptionType { … }

Generating & Handling Exceptions Java primitives Try Throw Catch Finally Procedure for using exceptions 1. Enclose code generating exceptions in try block 2. Use throw to actually generate exception 3. Use catch to specify exception handlers 4. Use finally to specify actions after exception

Java Syntax try {// try block encloses throws throw new eType1(); // throw jumps to catch } catch (eType1 e) { // catch block 1...action... // run if type match } catch (eType2 e) { // catch block 2...action... // run if type match } finally { // final block...action... // always executes }

Java Primitive – Try Forms try block Encloses all statements that may throw exception Scope of try block is dynamic Includes code executed by methods invoked in try block (and their descendents)

Java Primitive – Try Example try {// try block encloses all exceptions in A & B A( ); // exceptions may be caught internally in A & B B( ); // or propagated back to caller’s try block } void A( ) throws Exception { // declares exception B( ); } void B( ) throws Exception { // declares exception throw new Exception( ); // propagate to caller }

Java Primitive – Throw Indicates exception occurred Normally specifies one operand Object of class Exception When an exception is thrown 1. Control exits the try block 2. Proceeds to closest matching exception handler after the try block 3. Execute code in exception handler 4. Execute code in final block (if present)

Java Primitive – Catch Placed after try block Specifies code to be executed for exception Code in catch block  exception handler Catch block specifies matching exception type Can use multiple catch blocks for single try To process different types of exceptions First matching catch block executed Superclass may subsume catch for subclass If catch block for superclass occurs first

Java Primitive – Catch Example class eType1 extends Exception { … } try { … throw new eType1( ) … } catch (Exception e) { // Catch block 1...action... // matches all exceptions } catch (eType1 e) { // Catch block 2...action... // matches eType1 } // subsumed by block 1 // will never be executed

Java Primitive – Catch Can rethrow exception Exception propagated to caller(s) Example catch (ExceptionType e) { …// local action for exception throw e; // rethrow exception }// propagate exception to caller

Java Primitive – Finally Placed after try & all catch blocks Forms finally block Cleanup code Executed by all exception handlers Try restore program state to be consistent, legal Always executed Regardless of which catch block executed Even if no catch block executed Executed before transferring control to caller If exception is not caught locally

Designing & Using Exceptions Use exceptions only for rare events Not for common cases  checking end of loop High overhead to perform catch Place statements that jointly accomplish task into single try / catch block Use existing Java Exceptions if possible

Designing & Using Exceptions Avoid simply catching & ignoring exceptions Poor software development style Example try { throw new ExceptionType1( ); throw new ExceptionType2( ); throw new ExceptionType3( ); } catch (Exception e) { // catches all exceptions … // ignores exception & returns }

Summary Java primitives Try Forms try block Encloses all statements that may throw exception Throw Actually throw exception Catch Catches exception matching type Code in catch block  exception handler Finally Forms finally block Always executed, follows try block & catch code

Summary Programs often contain errors Exceptions  advanced Java language feature Java provides detailed support for exceptions Learn to use exceptions carefully