Chapter 10 – Exception Handling

Slides:



Advertisements
Similar presentations
Exception Handling. Introduction Errors can be dealt with at place error occurs –Easy to see if proper error checking implemented –Harder to read application.
Advertisements

Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
Java Exception Very slightly modified from K.P. Chow University of Hong Kong (some slides from S.M. Yiu)
 2003 Prentice Hall, Inc. All rights reserved. Chapter 15 – Exception Handling Outline 15.1 Introduction 15.2 Exception-Handling Overview 15.3 Exception-Handling.
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.
بسم الله الرحمن الرحيم CPCS203: Programming II. Objectives After you have read and studied this chapter, you should be able to –Improve the reliability.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 14 – Exception Handling Outline 14.1 Introduction 14.2 When Exception Handling Should Be Used 14.3.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Exceptions Chapter 18 Programs: DriverException2 DriverException TestAgeInputException.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
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
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other Error Handling Techniques 14.4The Basics.
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 14 - Exception Handling Outline 14.1Introduction 14.2When Exception Handling Should Be Used 14.3Other.
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.
Exception-Handling Fundamentals  A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of.
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:
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.
CSE 1201 Object Oriented Programming
Chapter 14 – Exception Handling
Exceptions In this lecture:
Exceptions: When things go wrong
OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Introduction to OO Program Design
COMPSCI 230 S Programming Techniques
Exceptions 10-Nov-18.
Exceptions 10-Nov-18.
Handling Exceptions.
Advanced Programming Behnam Hatami Fall 2017.
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.
Exceptions & exception handling
ATS Application Programming: Java Programming
Exceptions & exception handling
Chapter 12 Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Exception Handling Chapter 9 Edited by JJ.
Web Design & Development Lecture 7
Java Exception Very slightly modified from K.P. Chow
Exception Handling in Java
Java Exception Very slightly modified from K.P. Chow
Lecture 11 Objectives Learn what an exception is.
Java Exceptions Dan Fleck CS211.
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.
Chapter 12 Exception Handling and Text IO Part 1
Exceptions 10-May-19.
Java Basics Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 15 – Exception Handling
Presentation transcript:

Chapter 10 – Exception Handling What is an Exception? An exception is an event that occurs during the execution of a program which interrupts the normal flow of instructions. Examples - Divide a number by 0 Access an out-of-bounds array element Null Pointer reference Cannot convert a string to an integer .... and lots more.

Example > java AddTwoIntegersException public class AddTwoIntegersException { public static void main( String args[] ) { int num1, num2; num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } > java AddTwoIntegersException Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at AddTwoIntegersException.main(AddTwoIntegersException.java:5) > java AddTwoIntegersException A B Exception in thread "main" java.lang.NumberFormatException: For input string: "A" at java.lang.NumberFormatException.forInputString(NumberFormatException. java:48) at java.lang.Integer.parseInt(Integer.java:468) at java.lang.Integer.parseInt(Integer.java:518) at AddTwoIntegersException.main(AddTwoIntegersException.java:5)

How Java Handles Exception? When an error occurs within a Java method, the method creates an Exception object and hands it off to the runtime system. The runtime system is then responsible for finding some code to handle the error. In Java terminology, creating an exception object and handing it to the runtime system is called throwing an exception. After a method throws an exception, the runtime system will find someone to handle the exception.

How Java Handles Exception? void p() { try { f(); } catch (Exception e) { // something to do .....   void f() { g(); void g() { h(); void h() { // error occurs throw new Exception(); ...... The runtime system searches backwards through the call stack to find a method that contains an appropriate exception handler (see example at the right). The exception handler chosen is said to catch the exception. If no exception handler is found, the Java program terminates . 3 2 1

Throwing an Exception Handle Exception When an error occurs within a Java method, the method calls the throw statement to Indicates an exception has occurred. if (total < 0) throw new Exception("Negative Total"); Handle Exception Some exceptions (examples will be shown in next lecture) must be handled. Exception can be handled in a method in two ways: 1. Use a try-catch block to handle the exception 2. Rethrow the exception

try Blocks The try block structure try { statements that may throw an exception } catch ( ExceptionType1 exceptionReference1 ) { statements to process an exception } catch ( ExceptionType2 exceptionReference2 ) { statements to process an exception } ...... finally { statements always executed } A try followed by one or more of catch blocks finally block is optional Optional

Basics of Java Exception Handling Code that could generate errors put in try blocks Code for error handling enclosed in a catch block The finally always executes with or without an error

Example 1 public class CatchException1 { public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Invalid Number of arguments!"); System.out.println( "Usage : java AddTwoIntegers <num1> <num2>"); catch (NumberFormatException e) { System.out.println("Please enter integers!"); finally { System.out.println("Thank you for using this program."); >java CatchException1 Invalid Number of arguments! Usage : java AddTwoIntegers <num1> <num2> Thank you for using this program.

NumberFormatException ArrayIndexOutOfBoundsException Example 1 >java CatchException1 A B Please enter integers! Usage : java AddTwoIntegers <num1> <num2> Thank you for using this program. >java CatchException1 12 34 The sum is 46 Thank you for using this program. Example 2 Single catch can handle multiple exceptions The catch statement in the next example catches exception objects of Exception and all its subclasses. Exception NumberFormatException ArrayIndexOutOfBoundsException

Message stored in the Exception object e Example 2 public class CatchException2 { public static void main( String args[] ) { int num1, num2; try { num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]); System.out.println("The sum is " + (num1+num2)); } catch (Exception e) { System.out.println("The error : " + e.toString()); System.out.println( "Usage : java AddTwoIntegers <num1> <num2>"); Message stored in the Exception object e >java CatchException2 The error : java.lang.ArrayIndexOutOfBoundsException: 0 Usage : java AddTwoIntegers <num1> <num2> >java CatchException2 A B The error : java.lang.NumberFormatException: For input string: "A" Usage : java AddTwoIntegers <num1> <num2>

Throwing an Exception The throw statement is executed to indicate that an exception has occurred. This is called throwing an exception. Example class ComplexNum { private double real; private double imag;   public ComplexNum (double r, double i) { real = r; imag = i; } public ComplexNum divide(double d) throws Exception { if (d == 0.0) throw new Exception( "Attempted divide by zero in ComplexNum.divide"); return new ComplexNum(real/d, imag/d);

Throwing an Exception Note : The phrase throws Exception must be appended to the method header of divide to indicate that an object of Exception (or its subclass) may be thrown by the method. Otherwise the program cannot be compiled. class ComplexNum { private double real; private double imag; public ComplexNum Divide(double d) { if (d == 0.0) throw new Exception( "Attempted divide by zero in ComplexNum.divide");   return new ComplexNum(real/d, imag/d); } forgot to put throws Exception >javac ComplexNum.java ComplexNum.java:7: unreported exception java.lang.Exception; must be caught or declared to be thrown throw new Exception( ^ 1 error

throws Clause Lists the exceptions thrown by a method int functionName( paramterList ) throws ExceptionType1, ExceptionType2,… { // method body } RuntimeExceptions occur during execution ArrayIndexOutOfBoundsException NullPointerException too common Do not need to catch or rethrow - NOT a syntax error. But you must handle (either catch or rethrow) the Exception objects that are not created from the subclasses of RuntimeException - See the previous example.

Example 1 public class UsingExceptions1 { public static void main( String args[] ) { try { throwException(); } catch ( Exception exception ) { System.err.println( "Exception handled in main" ); public static void throwException() throws Exception { // throw an exception and immediately catch it System.out.println( "Method throwException" ); throw new Exception(); // generate exception System.err.println( "Exception handled in method throwException" ); throw exception; // rethrow for further processing finally { "Finally executed in throwException" ); >java UsingExceptions1 Method throwException Exception handled in method throwException Finally executed in throwException Exception handled in main

Example 2 public class UsingExceptions2 { public static void main( String args[] ) { try { throwException(); } catch ( Exception exception ) { System.err.println( "Exception handled in main" ); public static void throwException() throws Exception { // throw an exception and catch it in main System.out.println( "Method throwException" ); throw new Exception(); // generate exception catch( RuntimeException runtimeException ) { System.err.println( "Exception handled in method throwException" ); finally { System.err.println( "Finally is always executed" ); >java UsingExceptions2 Method throwException Finally is always executed Exception handled in main

Why using Exceptions? Standardized error handling policy. Separate error handling from the logic flow (no if-else statement). Force the programmer to handle the error. Can be used in Constructor.

Exception objects have several member methods, including: public void printStackTrace() Print a stack trace --- a list that shows the sequence of method calls up to this exception. public String getMessage() Return a string that may describe what went wrong.

Example 3 public class UsingExceptions3 { public static void main( String args[] ) { try { throwException(); } catch ( Exception e ) { System.err.println( "Exception handled in main" ); System.err.println( "Exception:" + e.getMessage() ); System.err.println( "Stack Trace: "); e.printStackTrace(); public static void throwException() throws Exception { System.out.println( "Method throwException" ); throw new Exception("My message"); >java UsingExceptions3 Method throwException Exception handled in main Exception:My message Stack Trace: java.lang.Exception: My message at UsingExceptions3.throwException(UsingExceptions3.java:16) at UsingExceptions3.main(UsingExceptions3.java:4)

How to write your own Exception You can write your own Exception class: The class should extend Exception (or its subclass) Pass the error message (string) to the superclass' constructor. class MyException extends Exception { public MyException() { super("The error message comes here"); }

How to write your own Exception class Main { public static void main(String s[]) { try { f(); } catch (MyException e) { System.out.println("Exception Caught: " + e); public static void f() throws MyException{ throw new MyException(); Output Exception Caught: MyException: The error message comes here