1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software.

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

Pearson Education, Inc. All rights reserved. 1.. Exception Handling.
1 Inheritance Classes and Subclasses Or Extending a Class.
1 Streams and Input/Output Files Part 2. 2 Files and Exceptions When creating files and performing I/O operations on them, the systems generates errors.
1 Arrays, Strings and Collections [1] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
1 Arrays, Strings and Collections [2] Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering.
Classes and Objects in Java
Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Error-handling using exceptions
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
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.
Chapter 8 Improving the User Interface
Yoshi
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 13 Exception Handling.
Exception Handling Xiaoliang Wang, Darren Freeman, George Blank.
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.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 10 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/ George Koutsogiannakis 1.
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.
Exceptions Briana B. Morrison CSE 1302C Spring 2010.
1 / 89 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 11 Programming Fundamentals using Java 1.
Understand Error Handling Software Development Fundamentals LESSON 1.4.
1 Lecture 11 Interfaces and Exception Handling from Chapters 9 and 10.
CSI 3120, Exception handling, page 1 Exception and Event Handling Credits Robert W. Sebesta, Concepts of Programming Languages, 8 th ed., 2007 Dr. Nathalie.
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. 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 and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
What is an exception? An exception is: – an event that interrupts the normal processing of the program. –an error condition that violates the semantic.
UNIT 3 TEMPLATE AND EXCEPTION HANDLING. Introduction  Program errors are also referred to as program bugs.  A C program may have one or more of four.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Exception. Runtime Error Consider the following program: public class BadArray { public static void main(String[] args) { // Create an array with three.
Exception Handling in JAVA. Introduction Exception is an abnormal condition that arises when executing a program. In the languages that do not support.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 10.
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.
Sheet 3 HANDLING EXCEPTIONS Advanced Programming using Java By Nora Alaqeel.
Exception Handling in Java Topics: Introduction Errors and Error handling Exceptions Types of Exceptions Coding Exceptions Summary.
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:
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
Exception Handling How to handle the runtime errors.
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 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.
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.
Chapter 10 – Exception Handling
MIT AITI 2003 Lecture14 Exceptions
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Multithreading 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.
Exception Handling and Reading / Writing Files
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.
Java Programming Exceptions CSC 444 By Ralph B. Bisland, Jr.
Tutorial Exceptions Handling.
Chapter 12 Exception Handling and Text IO Part 1
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.
Presentation transcript:

1 Exceptions: An OO Way for Handling Errors Rajkumar Buyya Grid Computing and Distributed Systems (GRIDS) Laboratory Dept. of Computer Science and Software Engineering University of Melbourne, Australia

2 Introduction Rarely does a program runs successfully at its very first attempt. It is common to make mistakes while developing as well as typing a program. Such mistakes are categorised as: syntax errors - compilation errors. semantic errors– leads to programs producing unexpected outputs. runtime errors – most often lead to abnormal termination of programs or even cause the system to crash.

3 Common Runtime Errors Dividing a number by zero. Accessing an element that is out of bounds of an array. Trying to store incompatible data elements. Using negative value as array size. Trying to convert from string data to a specific data value (e.g., converting string abc to integer value). File errors: opening a file in read mode that does not exist or no read permission Opening a file in write/update mode which has read only permission. Corrupting memory: - common with pointers Any more ….

4 Without Error Handling – Example 1 class NoErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; System.out.println(Result is + a/b); System.out.println(Program reached this line); } Program does not reach here No compilation errors. While running it reports an error and stops without executing further statements: java.lang.ArithmeticException: / by zero at Error2.main(Error2.java:10)

5 Traditional way of Error Handling - Example 2 class WithErrorHandling{ public static void main(String[] args){ int a,b; a = 7; b = 0; if (b != 0){ System.out.println(Result is + a/b); } else{ System.out.println( B is zero); } System.out.println(Program is complete); } Program reaches here

6 Error Handling Any program can find itself in unusual circumstances – Error Conditions. A good program should be able to handle these conditions gracefully. Java provides a mechanism to handle these error condition - exceptions

7 Exceptions An exception is a condition that is caused by a runtime error in the program. Provide a mechanism to signal errors directly without using flags. Allow errors to be handled in one central part of the code without cluttering code.

8 Exceptions and their Handling When the JVM encounters an error such as divide by zero, it creates an exception object and throws it – as a notification that an error has occurred. If the exception object is not caught and handled properly, the interpreter will display an error and terminate the program. If we want the program to continue with execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then take appropriate corrective actions. This task is known as exception handling.

9 Common Java Exceptions ArithmeticException ArrayIndexOutOfBoundException ArrayStoreException FileNotFoundException IOException – general I/O failure NullPointerException – referencing a null object OutOfMemoryException SecurityException – when applet tries to perform an action not allowed by the browsers security setting. StackOverflowException StringIndexOutOfBoundException

10 Exceptions in Java A method can signal an error condition by throwing an exception – throws The calling method can transfer control to a exception handler by catching an exception - try, catch Clean up can be done by - finally

11 Exception Handling Mechanism try Block Statements that causes an exception catch Block Statements that handle the exception Throws exception Object

12 Syntax of Exception Handling Code … try { // statements } catch( Exception-Type e) { // statements to process exception }..

13 With Exception Handling - Example 3 class WithExceptionHandling{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(Result is + r); } catch(ArithmeticException e){ System.out.println( B is zero); } System.out.println(Program reached this line); } Program Reaches here

14 Finding a Sum of Integer Values Passed as Command Line Parameters // ComLineSum.java: adding command line parameters class ComLineSum { public static void main(String args[]) { int InvalidCount = 0; int number, sum = 0; for( int i = 0; i < args.length; i++) { try { number = Integer.parseInt(args[i]); } catch(NumberFormatException e) { InvalidCount++; System.out.println("Invalid Number: "+args[i]); continue;//skip the remaining part of loop } sum += number; } System.out.println("Number of Invalid Arguments = "+InvalidCount); System.out.println("Number of Valid Arguments = "+(args.length-InvalidCount)); System.out.println("Sum of Valid Arguments = "+sum); }

15 Sample Runs java ComLineSum 1 2 Number of Invalid Arguments = 0 Number of Valid Arguments = 2 Sum of Valid Arguments = 3 java ComLineSum 1 2 abc Invalid Number: abc Number of Invalid Arguments = 1 Number of Valid Arguments = 2 Sum of Valid Arguments = 3

16 Multiple Catch Statements If a try block is likely to raise more than one type of exceptions, then multiple catch blocks can be defined as follows: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 }.. catch( Exception-TypeN e) { // statements to process exception N } …

17 finally block Java supports definition of another block called finally that be used to handle any exception that is not caught by any of the previous statements. It may be added immediately after the try block or after the last catch block: … try { // statements } catch( Exception-Type1 e) { // statements to process exception 1 }.. finally { …. } When a finally is defined, it is executed regardless of whether or not an exception is thrown. Therefore, it is also used to perform certain house keeping operations such as closing files and releasing system resources.

18 Catching and Propagating Exceptions Exceptions raised in try block can be caught and then they can be thrown again/propagated after performing some operations. This can be done by using the keyword throw as follows: throw exception-object; OR throw new Throwable_Subclass;

19 With Exception Handling - Example 4 class WithExceptionCatchThrow{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(Result is + r); } catch(ArithmeticException e){ System.out.println( B is zero); throw e; } System.out.println(Program is complete); } Program Does Not reach here when exception occurs

20 With Exception Handling - Example 5 class WithExceptionCatchThrowFinally{ public static void main(String[] args){ int a,b; float r; a = 7; b = 0; try{ r = a/b; System.out.println(Result is + r); } catch(ArithmeticException e){ System.out.println( B is zero); throw e; } finally{ System.out.println(Program is complete); } Program reaches here

21 Problem Statement : Consider the example of the Circle class Circle class had the following constructor public Circle(double centreX, double centreY, double radius){ x = centreX; y = centreY; r = radius; } How would we ensure that the radius is not zero or negative? User-Defined Exceptions Circle

22 Defining your own exceptions import java.lang.Exception; class InvalidRadiusException extends Exception { private double r; public InvalidRadiusException(double radius){ r = radius; } public void printError(){ System.out.println("Radius [" + r + "] is not valid"); }

23 Throwing the exception class Circle { double x, y, r; public Circle (double centreX, double centreY, double radius ) throws InvalidRadiusException { if (r <= 0 ) { throw new InvalidRadiusException(radius); } else { x = centreX ; y = centreY; r = radius; }

24 Catching the exception class CircleTest { public static void main(String[] args){ try{ Circle c1 = new Circle(10, 10, -1); System.out.println("Circle created"); } catch(InvalidRadiusException e) { e.printError(); }

25 User-Defined Exceptions in standard format class MyException extends Exception { MyException(String message) { super(message); // pass to superclass if parameter is not handled by used defined exception } class TestMyException { … try {.. throw new MyException(This is error message); } catch(MyException e) { System.out.println(Message is: +e.getMessage()); } Get Message is a method defined in a standard Exception class.

26 Summary A good programs does not produce unexpected results. It is always a good practice to check for potential problem spots in programs and guard against program failures. Exceptions are mainly used to deal with runtime errors. Exceptions also aid in debugging programs. Exception handling mechanisms can effectively used to locate the type and place of errors.

27 Summary Try block, code that could have exceptions / errors Catch block(s), specify code to handle various types of exceptions. First block to have appropriate type of exception is invoked. If no local catch found, exception propagates up the method call stack, all the way to main() Any execution of try, normal completion, or catch then transfers control on to finally block