Exception Handling in Java Reference: COS240 Syllabus

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

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 13 Exception.
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.
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:
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
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.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 14 Exception Handling and Text.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 12 Exception Handling and Text.
1 Chapter 18 Exception Handling. 2 Motivations F Program runs into a runtime error –program terminates abnormally F How can you handle the runtime error.
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Assertions Program correctness. Assertions Java statement – enables you to assert an assumption about your program. – An assertion contains a Boolean.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Exception Handling.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 15 Exceptions and.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Exception Handling and Text.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 11 Handling Exceptions and Events.
Exceptions and Assertions Chapter 15 – CSCI 1302.
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:
Liang,Introduction to Java Programming,revised by Dai-kaiyu 1 Chapter 15 Exceptions and Assertions Nothing is impossible.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
ECE122 L23: Exceptions December 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 24 Exceptions.
Lesson 4 Programming Techniques Exception Handling /EH/ AUBG ICoSCIS Team Assoc. Prof. Stoyan Bonev March, , 2013 SWU, Blagoevgrad.
Lecture 5: Exception Handling and Text File I/O Michael Hsu CSULA.
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.
Chapter 12 Exceptions and File Input/Output
Chapter 13 Exception Handling
Chapter 10 – Exception Handling
Chapter 12 Exception Handling And Text IO
MIT AITI 2003 Lecture14 Exceptions
Reference: COS240 Syllabus
Chapter 13 Exception Handling
Topic: Exception Handling
Chapter 12 Exception Handling and Text IO
Chapter 7 Exceptions and Assertions
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Exception Handling Chapter 9.
Chapter 12 Exception Handling
Abdulmotaleb El Saddik University of Ottawa
Chapter 11 Exception Handling and Text I/O
Exception Handling Chapter 9 Edited by JJ.
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Web Design & Development Lecture 7
Chapter 12 Exception Handling and Text IO
Chapter 14 Exception Handling and Text IO
Chapter 13 Exception Handling
Lecture 11 Objectives Learn what an exception is.
Chapter 12 Exception Handling and Text IO
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.
Chapter 14 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO Part 1
Chapter 12 Exception Handling and Text IO
Chapter 12 Exception Handling and Text IO
Java Basics Exception Handling.
Exception Handling.
Java Programming: From Problem Analysis to Program Design, 4e
Presentation transcript:

Exception Handling in Java Reference: COS240 Syllabus COS240 O-O Languages AUBG, COS dept Lecture 12 Title: Exception Handling in Java Reference: COS240 Syllabus

Lecture Contents: Part 1 Brief introduction to EH Part 2 Comprehensive introduction to EH

Part 1 Brief Intro to Exception Handling Exceptions An exception is an event that disrupts normal program flow.

Three approaches to error checking Ignore all but the most important errors. The code is cleaner, but the program will misbehave when it encounters an unusual error. Do something appropriate for every error. The code is cluttered, but the program works better. You might still forget some error conditions. Do the normal processing in one place, handle the errors in another (this is the Java and C# way). The code is at least reasonably uncluttered.

Java and C# approach: When an error occurs within a method (e.g. divide by zero; array index out of bounds; etc.), the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

The list of methods is known as the call stack After a method throws an exception, the runtime system attempts to find some code to handle it. The set of possible code to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack                                                                   The call stack.

The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system 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.

The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, the runtime system (and, consequently, the program) terminates.

The try statement Java provides a control structure, the try statement (also called the try-catch statement) to separate “normal” code from error handling: try { do the “normal” code, ignoring possible exceptions } catch (some exception) { handle the exception } catch (some other exception) { handle the exception }

Example try { result = numerator / denominator; validResult = true; } catch (ArithmeticException e) validResult = false;

try { do the “normal” code, ignoring possible exceptions } catch (some exception) { handle the exception } finally { ... }

System.out.println(e.getMessage()); Catching an Exception try { // normal code here! } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); // print call stack getMessage() is a method of the Throwable class that returns the error message describing the exception. printStackTrace() is also a method of the Throwable class What is the “dangerous code”? Any code involving one or more methods that throw exceptions. 12

Multiple catch Statements Order Matters! Less general first! try { // normal code here! } catch(ArithmeticException e) { // Specific error handling here catch(AnotherException e) { // More general error handling here Note that one catch is more general than the other. Also note that the more specific one here will override the more general one THE ORDER MATTERS HERE! 13

Part 2 Exception Handling in Details

Part 2 Lecture Contents: To get an overview of exceptions and exception handling. To explore the advantages of using exception handling. To distinguish exception types: Error (fatal) vs. Exception (nonfatal), and checked vs. unchecked. To declare exceptions in a method header. To throw exceptions in a method. To write a try-catch block to handle exceptions. To explain how an exception is propagated. To use the finally clause in a try-catch block. To use exceptions only for unexpected errors. To rethrow exceptions in a catch block. To create chained exceptions. To define custom exception classes.

Introduction When a program runs into a runtime error, the program terminates abnormally. In Java, runtime errors are caused by exceptions. An exception is an object that represents an error or an abnormal condition. If the exception is not handled, the program will terminate abnormally. How can you handle the runtime error so that the program can continue to run or terminate gracefully? This is the Exception Handling subject.

Exception-Handling Overview To demonstrate EH, including how an exception object is created and thrown: Open Quotient.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) FYI: FP real value divided by zero does not raise an exception.

Exception-Handling Overview Pure, naked, risky assignment statement quotient = dividend / divisor;

Exception-Handling Overview Simple way to fix the problem is to add if stmt to test the divisor: Open QuotientWithIf.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div)

Exception-Handling Overview User specified if statement if (divisor != 0) { quotient = dividend / divisor; System.out.println(dividend+" / "+divisor+" is = "+quotient); } else System.out.println("Divisor cannot be zero ");

Exception-Handling Overview To demonstrate EH, including how to create, throw, catch and handle an exception object: Open QuotientWithExcepionVerLiang.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div)

Exception-Handling Overview Explicitly written code to throw an exception try { … if (divisor == 0) throw new ArithmeticException("Divisor cannot be zero "); quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is = " + quotient); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: integer cannot divide by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } finally { System.out.println("\n\n Finally block executed"); }

Exception-Handling Overview To demonstrate EH, including how to create, throw, catch and handle an exception object: Open QuotientWithExcepionVerMalik.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div)

Exception-Handling Overview No explicit code to throw an exception Program implicitly creates exception and throws it try { … quotient = dividend / divisor; System.out.println(dividend + " / " + divisor + " is = " + quotient); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: integer cannot divide by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); } finally { System.out.println("\n\n Finally block executed"); }

Exception-Handling Overview Show runtime error Quotient Fix it using an if statement or using try … catch QuotientWithIf QuotientWithException What if the runtime error occurs in a called method? See next slide QuotientWithMethod

Exception-Handling Advantages To demonstrate EH advantages: Open QuotientWithMethod.java that reads two integers and displays their quotient. Run program with regular data Run program with illegal data (integer zero div) Now you see the advantages of using EH. It enables a method to throw an exception (implicitly or explicitly) to its caller. Without this capability, a method must handle the exception or terminate the program.

Exception-Handling Advantages Exception explicitly raised in one method Exception caught in another method public static int quotient(int num1, int num2) throws ArithmeticException { if (num2 == 0) throw new ArithmeticException("Divisor cannot be zero "); return num1/num2; } public static void main(String[] args) { try { result = quotient(dividend, divisor); System.out.println(dividend + " / " + divisor + " is = " + result); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: an integer cannot be divided by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); }

Exception-Handling Advantages Exception implicitly raised in one method Exception caught in another method public static int quotient(int num1, int num2) throws ArithmeticException { // if (num2 == 0) // throw new ArithmeticException("Divisor cannot be zero "); return num1/num2; } public static void main(String[] args) { try { result = quotient(dividend, divisor); System.out.println(dividend + " / " + divisor + " is = " + result); } // end of try catch (ArithmeticException aeRef) { System.out.println(" Exception: an integer cannot be divided by zero "); System.out.println(aeRef.getMessage()); aeRef.printStackTrace(); // print call stack } catch (InputMismatchException imeRef) { System.out.println(" Exception " + imeRef.toString() ); }

Handling InputMismatchException InputMismatchExceptionDemo Open DemoMismatchException.java that reads correctly input stream of integers. By handling InputMismatchException, your program will continuously read an input until it is correct.

Handling FileNotFoundException FileNotFoundExceptionDemo Open DemoFileNotFoundException.java that raises an exception in case of file not found.

The class Throwable has two direct subclasses, Exception and Error. Exceptions (members of the Exception family) are thrown to signal abnormal conditions that can often be handled by some code, though some may not be caught. Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. Errors are usually thrown by the methods of the Java API, or by the Java Virtual Machine itself.

Exception Types

System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.

Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.

Checked Exceptions vs. Unchecked Exceptions RuntimeException, Error and their subclasses are known as unchecked exceptions. All other exceptions are known as checked exceptions, meaning that the compiler forces the programmer to check and deal with the exceptions.

Unchecked Exceptions Unchecked exception.

Declaring, Throwing, and Catching Exceptions Java’s EH model is based on three operations: declaring an exception throwing an exception catching an exception

Declaring Exceptions Every method must state the types of checked exceptions it might throw. This is known as declaring exceptions. public void myMethod() throws IOException public void myMethod() throws IOException, OtherException

Throwing Exceptions throw new TheException(); When the program detects an error, the program can create an instance of an appropriate exception type and throw it. This is known as throwing an exception. Here is an example, throw new TheException(); TheException ex = new TheException(); throw ex;

Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }

Catching Exceptions try {// Statements that may throw exceptions When an exception is thrown, it can be caught and handled in a try-catch block as follows: try {// Statements that may throw exceptions statements; } catch (Exception1 exVar1) { handler for exception1; catch (Exception2 exVar2) { handler for exception2; ... catch (ExceptionN exVarN) { handler for exceptionN;

Catching Exceptions pp465

Catch or Declare Checked Exceptions Java forces you to deal with checked exceptions. If a method declares a checked exception (i.e., an exception other than Error or RuntimeException), you must invoke it in a try-catch block or declare to throw the exception in the calling method. For example, suppose that method p1 invokes method p2 and p2 may throw a checked exception (e.g., IOException), you have to write the code as shown in (a) or (b).

Example: Declaring, Throwing, and Catching Exceptions Objective: This example demonstrates declaring, throwing, and catching exceptions by modifying the setRadius() method in the Circle class. The new setRadius() method throws an exception if radius is negative. Open CircleWithException.java file TestCircleWithException CircleWithException

E.g.: Declaring, Throwing, and Catching Exceptions class Circle { … // methods mutators public void setRadius(double par) throws IllegalArgumentException { if (par >= 0.0) radius = par; else throw new IllegalArgumentException("Radius cannot be negative"); } … } // end of class Circle public class CircleWithException { public static void main(String[] args) { try { Circle a = new Circle(); Circle b = new Circle(5.); Circle c = new Circle(-5.); } catch (IllegalArgumentException ex){ System.out.println("\n-->>" + ex + "\n-->>"); System.out.println("\n-->>" + ex.getMessage() + "\n-->>"); ex.printStackTrace(); // print call stack } finally { System.out.println("\n Finally block executed"); } } // end of method main() } // end of class

Defining Custom Exception Classes Use the exception classes in the API whenever possible. Define custom exception classes if the predefined classes are not sufficient. Define custom exception classes by extending Exception or a subclass of Exception. the setRadius() method throws an exception if the radius is negative. Suppose you wish to pass the radius to the handler, you have to create a custom exception class. Open CircleWithUserException.java file

Defining Custom Exception Classes class IllegalRadiusException extends Exception { private double rad; public IllegalRadiusException(double radius) { // constructor super("Invalid radius " + radius); rad = radius; } public double getRad() { return rad; } } // end of class IllegalRadiusException class Circle { // methods mutators public void setRadius(double par) throws IllegalRadiusException { if(par >= 0.0) radius = par; else throw new IllegalRadiusException(par); } } // end of class Circle public class CircleWithUserException { public static void main(String[] args) { try { Circle a = new Circle(88.); //a.setRadius(-22.); Circle b = new Circle(5.); // Circle c = new Circle(-5.); } catch (IllegalRadiusException ex){ System.out.println("\n-->>\nInvalid radius is " + ex.getRad() + "\n-->>"); } } // end of method main() } // end of class

try { // normal code here! } catch(Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); // print call stack getMessage() is a method of the Throwable class that returns the error message describing the exception. printStackTrace() is also a method of the Throwable class

Rethrowing Exceptions try { statements; } catch(TheException ex) { // perform operations before exits; throw ex;

The finally Clause try { statements; } catch(TheException ex) { handling ex; finally { finalStatements;

Cautions When Using Exceptions (+) Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. () Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.

When to Throw Exceptions An exception occurs in a method. If you want the exception to be processed by its direct caller or by a method within the chain of its callers, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.

When to Use Exceptions? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null");

When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");

Assertions An assertion is a Java statement that enables you to assert an assumption about your program. An assertion contains a Boolean expression that should be true during program execution. Assertions can be used to assure program correctness and avoid logic errors.

Declaring Assertions assert assertion; or An assertion is declared using the new Java keyword assert in JDK 1.4 as follows: assert assertion; or assert assertion : detailMessage; where assertion is a Boolean expression and detailMessage is a primitive-type or an Object value.

Executing Assertions When an assertion statement is executed, Java evaluates the assertion. If it is false, an AssertionError will be thrown. The AssertionError class has a no-arg constructor and seven overloaded single-argument constructors of type int, long, float, double, boolean, char, and Object. For the first assert statement with no detail message, the no-arg constructor of AssertionError is used. For the second assert statement with a detail message, an appropriate AssertionError constructor is used to match the data type of the message. Since AssertionError is a subclass of Error, when an assertion becomes false, the program displays a message on the console and exits.

Executing Assertions Example To demonstrate effect of using assert keyword in Java: Open AssertionDemo.java source file. Compile and run the demo program.

Executing Assertions Example public class AssertionDemo { public static void main(String[] args) { int i; int sum = 0; for (i = 0; i <=10; i++) { sum += i; } assert i == 12; assert sum > 10 && sum < 5 * 10 : "sum is " + sum; System.out.println("\n\nExecution continues ..."); } }

Compiling Programs with Assertions Since assert is a new Java keyword introduced in JDK 1.4, you have to compile the program using a JDK 1.4 compiler. Furthermore, you need to include the switch –source 1.4 in the compiler command as follows: javac –source 1.4 AssertionDemo.java NOTE: If you use JDK 1.5, there is no need to use the –source 1.4 option in the command.

Running Programs with Assertions By default, the assertions are disabled at runtime. To enable it, use the switch –enableassertions, or –ea for short, as follows: java –ea AssertionDemo Assertions can be selectively enabled or disabled at class level or package level. The disable switch is –disableassertions or –da for short. For example, the following command enables assertions in package package1 and disables assertions in class Class1. java –ea:package1 –da:Class1 AssertionDemo

Using Exception Handling or Assertions Assertion should not be used to replace exception handling. Exception handling deals with unusual circumstances during program execution. Assertions are to assure the correctness of the program. Exception handling addresses robustness and assertion addresses correctness. Like exception handling, assertions are not used for normal tests, but for internal consistency and validity checks. Assertions are checked at runtime and can be turned on or off at startup time.

Using Exception Handling or Assertions, cont. Do not use assertions for argument checking in public methods. Valid arguments that may be passed to a public method are considered to be part of the method’s contract. The contract must always be obeyed whether assertions are enabled or disabled. For example, the following code should be rewritten using exception handling as shown in Lines 28-35 in Circle.java in Listing 13.8. public void setRadius(double newRadius) { assert newRadius >= 0; radius = newRadius; }

Using Exception Handling or Assertions, cont. Use assertions to reaffirm assumptions. This gives you more confidence to assure correctness of the program. A common use of assertions is to replace assumptions with assertions in the code.

Using Exception Handling or Assertions, cont. Another good use of assertions is place assertions in a switch statement without a default case. For example, switch (month) { case 1: ... ; break; case 2: ... ; break; ... case 12: ... ; break; default: assert false : "Invalid month: " + month }

Thank You for Your attention! Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807