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.

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

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 and Format output
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
MIT-AITI Lecture 14: Exceptions Handling Errors with Exceptions Kenya 2005.
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 Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
Java Exceptions. Types of exceptions  Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
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.
11-Jun-15 Exceptions. 2 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.
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.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
1 Exception Handling Introduction to Exception Handling Exception Handling in PLs –Ada –C++ –Java Sebesta Chapter 14.
CS 307 Fundamentals of Computer Science Java Basics - Exceptions and File I/O 1 Topic 4 Exceptions and File I/O "A slipping gear could let your M203 grenade.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
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.
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.
Object Oriented Programming
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.
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.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Class Design: Handling Errors Reading: 2 nd Ed: Chapter 15 3 rd Ed: Chapter 11 Exercises 2 nd Ed: P15.5, P15.6 (Hint: look at documentation for Scanner.
JSP Exception Handling 20-Oct-15. JSP - E XCEPTION H ANDLING When you are writing JSP code, a programmer may leave a coding errors which can occur at.
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.
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.
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.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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 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.
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.
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
Exceptions, Interfaces & Generics
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.
Web Design & Development Lecture 7
Managing Errors and 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.
Exceptions 10-May-19.
Java Basics Exception Handling.
Exception Handling and Event Handling
Presentation transcript:

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 unit." - THE U.S. Army's PS magazine, August 1993, quoted in The Java Programming Language, 3rd edition

When Good Programs Go Bad  A variety of problems can occur when a program is running. –User input error: bad url –Device errors: remote server unavailable –Physical limitations: disk full –Code errors: code that does not fulfill its contact (i.e. pre- and post-conditions)  When a problem occurs –return to safe state, save work, exit gracefully  Code that handles a problem may be far removed from code that caused it Computer Science II 2

How to Handle Problems?  It is possible to detect and handle problems of various types.  Issue: this complicates the code and makes it harder to understand. –The problem detection and problem handling code have little or nothing to do with the real code is trying to do.  A tradeoff between ensuring correct behavior under all possible circumstances and clarity of the code Computer Science II 3

Handling Problems in Java  Based on that of C++, but more in line with OOP philosophy  All errors/exceptions are objects of classes that are descendants of the Throwable class Computer Science II 4

Classes of Exceptions  The Java library includes two subclasses of Throwable interface: –Error Thrown by the Java interpreter for events such as heap overflow Never handled by user programs –Exception User-defined exceptions are usually subclasses of this Has two predefined subclasses: –IOException –RuntimeException Computer Science II 5

Error/Exception Classes Computer Science II 6

Throwable Interface Methods Methods with Description public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. public String toString() Returns the name of the class concatenated with the result of getMessage() public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace. Computer Science II 7

Exceptions  Many languages, including Java, use a mechanism know as exceptions to handle problems at runtime –In Java, Exception is a class with many descendants. –For example: ArrayIndexOutOfBoundsException NullPointerException FileNotFoundException ArithmeticException IllegalArgumentException Computer Science II 8

Handling Exceptions  Exceptions in Java fall into two different categories: –Checked (not Runtime) and Unchecked (Runtime) –Checked exception Must be caught in catch block Or declared in throws clause –Unchecked exception Need not be caught in catch block or declared in throws Exceptions that exist in code should be fixed Computer Science II 9

Unchecked Exceptions  Unchecked exceptions are completely preventable and should never occur. –Caused by logic errors, created by us, the programmers. –Descendents of the RuntimeException class  There does not need to be special error handling code –Just regular error prevention code  If error handling code was required, programs would be unwieldy Computer Science II 10

Unchecked Runtime Exceptions 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. Computer Science II 11

Checked Exceptions  "Checked exceptions represent conditions that, although exceptional, can reasonably be expected to occur, and if they do occur must be dealt with in some way.[other than the program terminating.]" –Java Programming Language, Third Edition  Checked exceptions represent errors that are unpreventable by us Computer Science II 12

Checked Runtime Exceptions ExceptionDescription ClassNotFoundExceptionClass not found. CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface. IllegalAccessExceptionAccess to a class is denied. InstantiationException Attempt to create an object of an abstract class or interface. InterruptedException One thread has been interrupted by another thread. NoSuchFieldExceptionA requested field does not exist. NoSuchMethodExceptionA requested method does not exist. Computer Science II 13

When Exceptions Occur  When an exception occurs, the normal flow of control of a program halts  The method where the exception occurred creates an exception object of the appropriate type –The object contains information about the error –Then hands the exception to the Java Runtime System  The Java Runtime System (JRS) searches for a matching catch block for the exception  The first matching catch block is executed  When the catch block code is completed, the program goes the next regular statement after the catch block Computer Science II 14

Call Stack  After a method throws an exception, the JRS looks for a method with a catch block to handle it. This block of code is called the exception handler. If the method that threw the exception can’t handle it, the JRS looks in the ordered list of methods that have been called to get to this method. This list of methods is known as the call stack. Computer Science II 15

Exception Handler  The search for an exception handler starts with the method where the error occurred. The search then proceeds down the call stack. When an appropriate handler is found, the JRS passes the exception to the handler. An exception handler is considered appropriate if the type of the exception object thrown matches the type that can be handled by the handler. Computer Science II 16

Catching Exceptions  The exception handler chosen is said to catch the exception. If the JRS the whole call stack without finding an appropriate exception handler, the JRS and the program terminate. Computer Science II 17

Catching Exceptions  Method uses a try block around code that may cause an exception.  Catch statement declares type of exception trying to catch. If an exception occurs of that type, the exception is passed on to that block for processing. Computer Science II try { //Protected code } catch(ExceptionName e1) { //Catch block } 18

An Example Computer Science II // File Name : ExcepTest.java import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } 19

Example – cont’d  The above code would produce the following result: Computer Science II Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block 20

Multiple Catch Blocks  A try block can be followed by multiple catch blocks. Computer Science II try { //Protected code } catch(ExceptionType1 e1) { //Catch block } catch(ExceptionType2 e2) { //Catch block } catch(ExceptionType3 e3) { //Catch block } 21

Example-Multiple Catch Blocks Computer Science II try { file = new FileInputStream(fileName); x = (byte) file.read(); } catch(FileNotFoundException f) { f.printStackTrace(); return -1; } catch(IOException i) { i.printStackTrace(); return -1; } 22

throws / throw Keywords  If a method does not handle a checked exception, the method must declare it using the throws keyword. Computer Science II import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } 23

Multiple Exceptions Thrown  A method can throw more than one exception –Exceptions are declared in a list separated by commas. Computer Science II import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition } 24

finally Block  The finally keyword used to create a block of code that follows a try block. –always executes, whether or not an exception has occurred. –run any cleanup-type statements that you want to execute –appears after the catch blocks Computer Science II try { //Protected code } catch(ExceptionType e) { //Catch block } finally { //The finally block always executes. } 25

Example – finally Block Computer Science II public class ExcepTest { public static void main(String args[]) { int a[] = new int[2]; try { System.out.println("Access element three :" + a[3]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } finally { a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } 26

finally Block Example – cont’d  Would produce this result: Computer Science II Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed 27

Things to Note  Must follow a try block with either catch and/or finally block.  Catch blocks must follow a try statement.  A finally block is not required if there are try-catch blocks.  try, catch, finally blocks must follow each other in that order –There cannot be any code cannot between them. Computer Science II 28

Throwing Exceptions Yourself  If you wish to throw an exception in your code, you use the throw keyword  Most common would be for an unmet precondition public class Circle {private int iMyRadius; /** pre: radius > 0 */ public Circle(int radius) {if (radius <= 0) throw new IllegalArgumentException ("radius must be > 0. " + "Value of radius: " + radius); iMyRadius = radius; } Computer Science II 29

Creating Exceptions  All exceptions must inherit from the Throwable class.  If you want to write a checked exception, extend the Exception class.  If you want to write a runtime exception, extend the RuntimeException class.  Define at least two constructors 1.Default, no parameters 2.Other with String parameter –For both, call constructor of base class using super  Do not override inherited getMessage Computer Science II 30

Example–Creating Exceptions Computer Science II // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } 31

Example – cont’d Computer Science II // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int accountNumber; public CheckingAccount(int accountNumber) { this.accountNumber = accountNumber; } public void deposit(double amount) { balance += amount;} public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } public double getBalance() { return balance; } } 32

Example - concluded Computer Science II // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); } catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } 33

Errors  An error is an object of class Error –Similar to an unchecked exception –Need not catch or declare in throws clause –Object of class Error generated when abnormal conditions occur  Error s are more or less beyond your control –Require change of program to resolve Computer Science II 34

Question 1 What is output by the method badUse if it is called with the following code? int[] nums = {3, 2, 6, 1}; badUse( nums ); public static void badUse(int[] vals){ int total = 0; try{ for(int i = 0; i < vals.length; i++){ int index = vals[i]; total += vals[index]; } } catch(Exception e){ total = -1; } System.out.println(total); } A. 1 B. 0 C. 3 D. -1 E. 5 Computer Science II 35

Question 2 Is the use of a try-catch block on the previous question a proper use of try- catch blocks? A. Yes B. No Computer Science II 36

Computer Science II Assertions  Statements in the program declaring a Boolean expression about the current state of variables  If evaluate to true, nothing happens  If evaluate to false, an AssertionError exception is thrown  Can be disabled during runtime without program modification or recompilation  Two forms –assert condition ; –assert condition : expression ; 37

Error Handling, Error Handling Everywhere!  Seems like a lot of choices for error prevention and error handling –normal program logic (e.g. if s, for -loop counters) –assertions –try-catch block  When is it appropriate to use each kind? Computer Science II 38

Error Prevention  Use program logic ( if s, for s) to prevent logic errors and unchecked exceptions –dereferencing a null pointer –going outside the bounds of an array –violating the preconditions of a method you are calling Computer Science II 39

Error Prevention – cont’d  In general, don’t use asserts to check preconditions –Standard Java style is to use exceptions  Use try-catch blocks on checked exceptions –Don’t use them to handle unchecked exceptions, like null pointer or array index out of bounds  One place it is reasonable to use try- catch is in testing suites. –put each test in a try-catch. If an exception occurs that test fails, but other tests can still be run Computer Science II 40

Advantages of Exceptions 1.Separating Error-Handling Code from "Regular" Code –Means to separate the details of what to do when something out of the ordinary happens from the main logic of a program. 2.Propagating Errors Up the Call Stack –Ability to propagate error reporting up the call stack of methods. 3.Grouping and Differentiating Error Types –All exceptions thrown within a program are objects, the grouping or categorizing of exceptions is a natural outcome of the class hierarchy. Computer Science II 41