Exception Handling 1. Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected.

Slides:



Advertisements
Similar presentations
Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
Advertisements

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.
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.
An Introduction to Java Programming and Object- Oriented Application Development Chapter 8 Exceptions and Assertions.
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.
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.
Exception Handling 1 CISC6795, Spring Introduction 2 Exception – an indication of a problem that occurs during a program’s execution, for examples:
© The McGraw-Hill Companies, 2006 Chapter 15. © The McGraw-Hill Companies, 2006 Exceptions an exception is an event that occurs during the life of a program.
 2005 Pearson Education, Inc. All rights reserved Exception Handling.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Exception Handling 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
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.
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 in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Exception Handling (in a nutshell). 2 Motivations When a program runs into a runtime error, the program terminates abnormally. How can you handle the.
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.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
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
June 14, 2001Exception Handling in Java1 Richard S. Huntrods June 14, 2001 University of Calgary.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
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.
Exceptions "A slipping gear could let your M203 grenade launcher fire when you least expect it. That would make you quite unpopular in what's left of your.
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.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Programming in C++ 1. Learning Outcome At the end of this slide, student able to:  Identify the different types of error in your program  Understand.
Slides Credit Umair Javed LUMS Web Application Development.
COMP Exception Handling Yi Hong June 10, 2015.
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.
Android How to Program, 2/e © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Unit 4 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
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.
Exceptions Handling Prepared by: Ligemm Mae del Castillo.
Programming & Debugging. Key Programming Issues Modularity Modifiability Ease of Use Fail-safe programming Style Debugging.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Exceptions in OO Programming Introduction Errors Exceptions in Java Handling exceptions The Try-Catch-Finally mechanism Example code Exception propagation.
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.
Exception Handling. You learned that there are three categories of errors: syntax errors, runtime errors, and logic errors. Syntax errors arise because.
Object Throwable ErrorException RuntimeException.
Eighth Lecture Exception Handling in Java
Tirgul 13 Exceptions 1.
Chapter 12 Exception Handling
Exception Handling and Reading / Writing Files
Managing Errors and Exceptions
Chapter 12 Exception Handling and Text IO Part 1
Java Basics Exception Handling.
Exception Handling.
Presentation transcript:

Exception Handling 1

Introduction Users may use our programs in an unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution, or may result in an abnormal program termination It is our responsibility to produce robust code that does not fail unexpectedly. Consequently, we must design error handling into our programs. 2

Errors and Error Handling Some typical causes of errors: File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down, URL does not exist) Calculation errors (i.e. divide by 0) More typical causes of errors: Array errors (i.e. accessing element –1) Conversion errors (i.e. convert ‘q’ to a number) 3

Exceptions What are they? An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. 4

Checked Exceptions How are they used? Exceptions fall into two categories: Checked Exceptions Unchecked Exceptions Checked exceptions are inherited from the core Java class Exception. They represent compile time exceptions that are your responsibility to check. Checked exceptions must be handled in your code. Otherwise, the compiler will issue an error message. 5

Unchecked Exceptions Unchecked exceptions are runtime exceptions that result at runtime from conditions that you should not have allowed in the first place (inherited from RuntimeException). You do not have to do anything with an unchecked exception. But, if not handled, your program will terminate with an appropriate error message. 6

Checked Exceptions 7 ExceptionDescription ClassNotFoundExceptionClass not found. CloneNotSupportedExceptionAttempt to clone an object that does not implement the Cloneable interface. IllegalAccessExceptionAccess to a class is denied. InstantiationExceptionAttempt to create an object of an abstract class or interface. InterruptedExceptionOne thread has been interrupted by another thread. NoSuchFieldExceptionA requested field does not exist. NoSuchMethodExceptionA requested method does not exist.

ExceptionDescription ArithmeticExceptionArithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds. ArrayStoreExceptionAssignment to an array element of an incompatible type. ClassCastExceptionInvalid cast. IllegalArgumentExceptionIllegal argument used to invoke a method. IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread. IllegalStateExceptionEnvironment or application is in incorrect state. IllegalThreadStateExceptionRequested operation not compatible with current thread state. IndexOutOfBoundsExceptionSome type of index is out-of-bounds. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. NumberFormatExceptionInvalid conversion of a string to a numeric format. SecurityExceptionAttempt to violate security. StringIndexOutOfBoundsAttempt to index outside the bounds of a string. UnsupportedOperationExceptionAn unsupported operation was encountered. 8 Unchecked Exceptions

Definitions Stack trace Name of the exception in a descriptive message that indicates the problem Complete method-call stack exceptionObject.printStackTrace(); Exception message: returns a detailed message which describes the exception. exceptionObject.getMessage(); 9

Exception Handling Exception handling is accomplished through 1. the “try – catch” mechanism: handle the exception by yourself, 2. or by a “throws” clause in the method declaration: pass exception handling “up the chain”. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception up the chain. 10

Coding Exceptions Try-Catch Mechanism Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword. If none of the code inside the try block throws an exception, then the program skips the catch clause. 11

Coding Exceptions Example try { … normal program code } catch(ArithmeticException AEx){ … } catch(Exception e) { … exception handling code } finally{ … code to close some files or release resources } 12

finally Block Consists of finally keyword followed by a block of code enclosed in curly braces Optional in a try statement This block contains code that is ALWAYS executed whether or not an exception is thrown in the corresponding try block or any of its corresponding catch blocks. If present, is placed after the last catch block Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file) 13

Using the throws Clause Exceptions can be thrown by statements in method’s body or by methods called in method’s body Exceptions can be of types listed in throws clause or subclasses 14

Coding Exceptions Passing the exception In any method that might throw an exception, you may declare the method as “throws” that exception, and thus avoid handling the exception yourself. You are not allowed to add more throws specifiers to a subclass method than are present in the superclass method. Example public void myMethod throws IOException { … normal code with some I/O … throw new IOException(); } 15

Example1: un-handled exception 16

Example 2: Handled Exception 17

Output of Handled Exception Example 18

Example 3 19

Output of Example 3 20

Example 4 21

Example 5 22