1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.

Slides:



Advertisements
Similar presentations
Topics Introduction Types of Errors Exceptions Exception Handling
Advertisements

Exceptions: when things go wrong. Various sources of error public static doSomething() { int i = 3.0; while(!done); { int i = false } ) Syntactic errors.
CMSC 202 Exceptions 2 nd Lecture. Aug 7, Methods may fail for multiple reasons public class BankAccount { private int balance = 0, minDeposit =
Exceptions & exception handling Use sparingly. Things you can do with exceptions: 1. Define a new exception class. 2. Create an exception instance. 3.
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
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.
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.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
EXCEPTIONS Def: An exception is a run-time error. Examples include: attempting to divide by zero, or manipulate invalid data.
1 Repetition structures Overview while statement for statement do while statement.
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.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Java Exception Handling ● Exception = an event that occurs during the execution of a program that disrupts the normal flow of instructions: – Examples:
Chapter 11: Handling Exceptions and Events J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Fourth.
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Object Oriented Programming
Program Errors Syntax errors Logic errors
CIS 270—Application Development II Chapter 13—Exception Handling.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
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.
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.
1 Advanced Flow of Control : Introduction This chapter focuses on: –exception processing –catching and handling exceptions –creating new exceptions –exception.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
Exceptions and Assertions Chapter 15 – CSCI 1302.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
Exceptions. Exception  Abnormal event occurring during program execution  Examples Manipulate nonexistent files FileReader in = new FileReader("mumbers.txt“);
Copyright © Curt Hill Error Handling in Java Throwing and catching exceptions.
OOP (Java): Exceptions/ OOP Objectives – –examine Java's exception handling Semester 2, Exceptions.
(c) University of Washington10-1 CSC 143 Java Errors and Exceptions Reading: Ch. 15.
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:
Exceptions an unusual condition – e.g. division by zero – e.g. file doesn't exist – e.g. illegal type – etc. etc… typically a run-time error – i.e. during.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
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.
Chapter 10 – Exception Handling
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
CS1101: Programming Methodology Recitation 7 – Exceptions
Introduction to Exceptions in Java
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.
Web Design & Development Lecture 7
Exception Handling in Java
Lecture 11 Objectives Learn what an exception is.
CMSC 202 Exceptions 2nd Lecture.
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.
Tutorial Exceptions Handling.
Exception Handling Contents
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions  What exceptions should be handled?  How exceptions are handled  Unreachable catch-blocks  The semantics of the try statement  Recovering from Exceptions

2 Introduction to Exceptions  A program may have one or more of three types of errors:  Syntax errors or Compile-time errors.  Run-time or Execution-time errors.  Logic errors.  A Java exception is an object that describes a run-time error condition that has occurred in a piece of Java code or in the Java run-time System.  All Java exception classes are subclasses of the Throwable class.  Most exception classes are defined in the java.io and java.lang packages.  Other packages like: java.util, java.awt, java.net, java.text also define exception classes.  A piece of Java code containing statements to handle an exception is said to catch the exception; otherwise it is said to throw that exception.

3 How Exceptions are Generated  Exceptions can be generated in two ways:  By the Java run-time system.  By the programmer using the throw statement.  Common forms of the throw statement are:  throw new ThrowableClass();  throw new ThrowableClass(string); where ThrowableClass is either Throwable or a subclass of Throwable.  Examples: if(divisor == 0) throw new ArithmeticException(“Error - Division by zero”); if(withdrawAmount < 0) throw new InvalidArgumentException(“Error – Negative withdraw amount”); else balance -= withdrawAmount;

4 A partial hierarchy of Java exceptions

5 Checked and Unchecked Exceptions  Java exceptions are classified into two categories: checked exceptions and unchecked exceptions:  Checked exception: An object of Exception class or any of its subclasses except the subclass RunTimeException.  Unchecked exception:  An object of the Error class or any of its subclasses.  An object of RunTimeException or any of its subclasses.  A method that does not handle checked exceptions it may generate, must declare those exceptions in a throws clause; otherwise a compile-time error occurs.  A method may or may not declare, in a throws clause, unchecked exceptions it may generate but does not handle.  Syntax of a throws clause: accessSpecifier returnType methodName(parameters)throws ExceptionType1, ExceptionType2,..., ExceptionTypeN { // method body }  Note: When a method declares that it throws an exception, then it can throw an exception of that class or any of its subclasses.

6 Checked and Unchecked Exceptions (cont’d)  Examples: public static void main(String[] args) throws IOException{ //... String name = stdin.readLine(); //... } If IOException is not handled, the throws IOException is required public static void main(String[] args){ //... int num1 = num2 / num3; //... } Statement will generate ArithmeticException if num3 is zero. The method may or may not contain a throws ArithmeticException clause

7 What exceptions should be handled?  Exceptions of class IOException and its subclasses should be handled.  They occur because of bad I/O operations (e.g., trying to read from a corrupted file).  Exceptions of class RuntimeException and its subclasses and all subclasses of Exception (except IOException) are either due to programmer-error or user-error.  Programmer-errors should not be handled. They are avoidable by writing correct programs.  User-errors should be handled.  o Example: Wrong input to a method may generate:  ArithmeticException, IllegalArgumentException, or NumberFormatException.  The exceptions of class Error and its subclasses should not be handled.  They describe internal errors inside the Java run-time system. There is little a programmer can do if such errors occur.  Examples: OutOfMemoryException, StackOverflowException.

8 How exceptions are handled  Java uses try-catch blocks to handle exceptions.  try-catch blocks have the form: try{ statementList } catch(ExceptionClass1 variable1){ statementList } catch(ExceptionClass2 variable2){ statementlist }... catch(ExceptionClassN variableN){ statementlist }  A statement or statements that may throw exceptions are placed in the try-block.  A catch-block defines how a particular kind of exception is handled.

9 Unreachable catch-blocks  A catch-block will catch exceptions of its exception class together with any of its subclasses.  Example: Since ArithmeticException is a subclass of Exception, the following code will cause compile-time error because of unreachable code: try{ int a = 0; int b = 42 / a; } catch(Exception e){ System.out.println(e); } catch(ArithmeticException e){ System.out.println(“There is an arithmetic exception”); }

10 The semantics of the try statement  A catch block cannot catch an exception thrown by another try block, except in the case of nested try blocks.  When a try block is executed, there are three possible cases: 1. No exception is generated:  All the statements in the try block are executed.  No catch block is executed.  Processing continues with the statement following all the catch blocks for the try block. 2. An exception is thrown and there is a matching catch block.  The statements in the try block following the statement that caused the exception are NOT executed.  The first matching catch block is executed.  No other catch block is executed.  Processing continues with the statement following all the catch clauses for the try block. 3. An exception is thrown and there is no matching catch block.  Control is immediately returned (propagated) to the method that called this method that caused the exception.  The propagation continues until the exception is caught, or until it is passed out of the Java program, where it is caught by the default handler in the Java-runtime System.  The default exception handler displays a string describing the exception.

11 Recovering from Exceptions  The code to recover from an exception is usually a loop that repeats as long as the condition that causes the exception has not been removed.  Example: import java.io.*; public class TestException{ public static void main(String[] args)throws IOException{ BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); int number = 0; boolean done = false; do{ try{ System.out.println(“Enter an integer: “); number = Integer.parseInt(stdin.readLine().trim()); done = true; } catch(NumberFormatException e){ System.out.println(“Error - Invalid input!”); } }while(! done); System.out.println(“The number entered is “ + number); }

12 Recovering from Exceptions (cont’d)  Example: import java.io.*; class BankAccount{ private int accountNumber; private double balance; public void deposit(double amount){ if(amount < 0) throw new IllegalArgumentException(“Negative deposit”); else balance += amount; } //... } public class BankAccountTest{ public static void main(String[] args)throws IOException{ //... boolean done = false; do{ System.out.println(“Enter amount to deposit:”); double amount = Double.parseDouble(stdin.readLine()); try{ account.deposit(amount); done = true; } catch(IllegalArgumentException e){System.out.println(e);} }while(! done); }