Exceptional Handling:

 

Run-time Error:

 

                Run-time errors in computer programming are a big problem and handling these errors is serious business.  Errors normally are divided into several categories and handling them was never addressed in any programming language except the <assert.h> header file in C.  Every programmer was left to find and handle errors with whatever methods could be created.  The Switch statement with the default case was the way to handle errors and still is a good way.  There was no built-in error handler in any language and C++ introduced the error handler as User-Defined methods or classes.

 

                The assert macro in C was used to print to the standard error an error message, which is composed of a message, a file name and a line number.  It also terminates the execution of the program.  The following is the Microsoft assert.h header file.

 

 

#define assert(exp) (void)( (exp) || (_assert(#exp, __FILE__, __LINE__), 0) )

 

Test Case:

 

Example # 1 declares the “DivideByZero” class, which is an application with a statement where there is a division by ZERO.  This application execution should be terminated at the point where the division by zero statement is executed.  The code prompts the user with "Press Enter key to continue" before the run-time error and the termination of the application execution. This is an illustration of why exceptional handling code is needed.  The output is a screen print of Microsoft J++ with an error window and is shown in Figure # 1.

 

 

Example # 1:

/***********************************************************************

** This program is an application with a statement where there is a division by ZERO.

************************************************************************/

public class DivideByZeroProg

{

public DivideByZeroProg()

{

final int   ZERO = 0;

int         IntegerValue;

float       FloatValue;

 

IntegerValue = 2;

FloatValue = 10 / IntegerValue;

System.out.println("10 / 2 = \t" + FloatValue);

// can not divide by 0 directly, must use a property(variable)

IntegerValue = ZERO;

// prompt before bombing

System.out.println("Press Enter key to continue");

                                try

                {

                                                System.in.read();

                }

                                catch(Exception myException)

                {// do nothing

                                }

 

FloatValue = 10 / IntegerValue;

System.out.println("10 / 2 = \t" + FloatValue);

}

//***************************************************

public static void main(String [] args)

{

DivideByZeroProg  MyDivideByZeroProg = new DivideByZeroProg();

                try

                                {

                                System.in.read();

                                }

                catch(Exception myException)

                                {// do nothing

                }

}

}

 

Output:

10 / 2 =        5.0

Press Enter key to continue

 

 


                                                                Figure # 1 – Exception

 

 


Errors:

 

Errors in Java are categorized into two types.  The first error type is a non-recoverable error, which should not be handled and the Java interpreter would display an error message and terminate the application or applet.  For example, stack over flow with recursion.  The second type is a death threat error where the programmer code can handle such errors.  Java calls these kinds of death threat errors Exceptions.

 

An exception is a signal that an abnormal condition is taking place that may terminate the program.  An exception may be caught and handled.

 

 

Java Class and Subclasses – First Visit:

 

Java class provides a new way of declaring a user-defined data type that has functionality. This user-defined data type contains both the data objects and the methods that perform certain tasks on them.  A class is a way of grouping logical data and the associated methods within one object (class).

 

public class myClassName

{

member data list                   - 0 or more

// variables which are known as properties

member method list              - 0 or more

public static void main(String [] args)

{…}

}

 

Inheritance:

 

Inheritance is a mechanism that allows type and subtype share characteristics the same way genes are passed from parents to children. Java inheritance is implemented through the mechanism called extending class.  Inheritance allows the member of one class to be used by another class as if the members of the inherited class (extended) were the members of inheritee class.  Inheritance is the relationship between the parent class and child class.  The parent class is called “super-class” and child is “subclass”. The super-class members can be referenced by the subclass and are said to be inherited by the subclass. Java allows only single inheritance, and complements the absence of multiple-inheritance with another mechanism known as the implementation of interfaces.

 

 

Super-Class (Base class):

 

A super-class is a previously declared class for the class being declared. A class is said to be extended from its super-class.  Super-class is also known as a base class.

 

 

class mySuperClass

{

                int           mySuperClassInteger  = 10;

 

public mySuperClass()

{…}

 //***********************************************

void mySuperClassMethod()

{…}

}

//************************************************

public class mySubClass extends mySuperClass

{

public mySubClass()

{

                mySuperClassInteger          =  20;

                mySuperClassMethod();

               

}

}

 

The above code declares a super-class and its subclass, where the subclass can access the super-class member as if they were its own members.

 

 

Throwable Class:

 

                Java has a class called “Throwable” which is the base class for all the exceptions. “Throwable” has two subclasses named “Error” and “Exception”.   “Throwable” class methods can be used to display error messages as well as a stack trace of the exceptions occurred.  The following is some of the Java “Throwable” class constructors and methods:

 

1.        public Throwable();  // constructor

2.        public Throwable(String Message); // constructor

3.        public String getMessage();

4.        public Throwable fillInStackTrace();

5.        public void printStackTrace();

6.        public void printStackTrace(PrintStream Our PrintStream);

7.        public String  toString();

 

 

Programmers can create their own exception handling classes or methods.

 

 

Programmer Exception Handling:

 

                The idea behind exception handling is to create traps to known errors and handle them in the proper way using the programmer code.  The programmer has the option to create a class or method, and force every one who calls or uses the programmer created class or method to provide code to handle whatever the programmer lists as an exception.   For example, a programmer can create a method to trap zero values and throws an IO exception flag (clause) stating that any caller to the programmer trap zeros method must provide code to handle the error of the zero trap method.  The Java compiler will enforce the programmer request for the needed code, and the application or the applet will not compile if the requested code is not found.  Exceptions are enforced at compile time.

 

                int  TrapZeros(int  PassedInteger)

                                throws IOException             // let every one knows there is an exception to be handled.

                {

                                if (0 == PassedInteger)

                                   throws new IOException();

                                return(PassedInteger);

                }

 

 

The above code has a method called “TrapZeros” that takes an integer as a parameter and returns an integer.  This method throws an IOException if its parameter is equal to zero, which is an indication to the compiler that anyone who makes a call to the “TrapZeros” method must have the proper code to handle such an exception.  The compiler will enforce the throws of an exception, and an application or an applet will not compile unless the proper code is present. 

 

What is the proper code that is needed?

 

The needed code is divided into two parts, the first is the method or the class that is throwing an exception and the second is the caller to this method or instantiator of the class. 

 

The method that is throwing the exception has to create an exception instance of the type of exception.  For example, “TrapZeros” method has the following code as an indication to the compiler that it is throwing an exception with the “IOException()” type:

 

                                   throws new IOException();

 

The caller must provide “try” and “catch” clauses as the caller required code to handle the exception.

 

 

try, catch and finally Clauses:

 

                Once a method throws an exception, then the caller to this method must do the following:

 

1.        Use a “try” clause to execute the method (calls the method)

2.        Provide a “catch” clause if there is an error.

3.        There is an option code clause called ”finally” that will be executed regardless if an error occurred or not.

 

The method that would call “TrapZeros” may have the following code.

 

                void  CallTrapZerosMethod()

                {

                               

                                try           // must make a call to the TrapZero  method within “try” clause.

                                {

                                   MyValue = TrapZeros(MyInteger);

                                  

                                }

                                catch(IOException MyIOException)

                                {

                                  System.out.println(“Error…..”);

                                // two of Throwable class methods – getMethod and printStackTrace

  String ErrorMessage = MyIOException.getMessage();

  System.out.println("ErrorMessage = " + ErrorMessage);

  MyIOException.printStackTrace();

                                  return;

                                }

                                finally     // optional

                                {

                                  // … whatever must be done

                                  // code that must be executed.

                                }

                                DoYourNormalThingMethod();

                                … //   the remaining of CallTrapZerosMethod method code

                }

 

 

The above code has a method called “CallTrapZerosMethod” which makes a call to “TrapZeros” method mentioned earlier.  In order for the above code to compile since “TrapZeros” throws an IOException, the “CallTrapZerosMethod” method must have a “try” clause or block.  Within this “try” clause, the call to “TrapZeros” is made.  Following the “try” clause, a “catch” clause must also be provided.  Note that the “catch” clause has an argument of the exception type, which is “IOException”.  This is a declaration of the same exception that is thrown by “TrapZeros” method.  This exception declaration is used as an identification of the type of exception in case of multiple exceptions.  It also creates a system object  (“MyIOException “) that can be used to call the exception (Java built-in) methods associated with this exception type “MyIOException.printStackTrace()”.

 

 

                                catch(IOException MyIOException)

                                {

                                               

String ErrorMessage           = MyIOException.getMessage();

MyIOException.printStackTrace();

                                }

 

 

Within the “catch“ clause, the caller can write any code the caller wishes to handle the error with or can do nothing by having an opened and closed curly brackets “{}” with nothing between them.  The above “catch” clause has code that makes a call to each of the java.lang.Throwable.getMethod() and java.lang.Throwable.printStackTrace() methods to illustrate some of the methods or code that the caller can write to handle the exception.  The “return”, “break” or “continue” statement may be added to the code of the “catch” clause as it is shown .

 

                                catch(IOException MyIOException)

                                {

                                                return;

                }

 

Test Case:

 

                The goal of Example # 2 is to illustrate the sequence of execution of the “try” and “catch” clauses with an error and without an error. Every method and the “try” and “catch” clauses print a message to indicate their sequence of execution.  Example # 2 code declares “ExceptionHandling_1” class, which declares the “CatchDivideByZeroMethod()”, “Method_1”and “Method_2” methods.  The “CatchDivideByZeroMethod()” method throws an exception. The other two methods call the “CatchDivideByZeroMethod()”  method and need the code to handle the exception thrown by the “CatchDivideByZeroMethod()” method.  The “new” operator is used to create the “ArithmeticException “ exception.

 

if(0 == DivideByInteger)

    throw new ArithmeticException();

 

The first method “Method_1” is designed to have an error and the “catch” clause is executed. The “Method_2” method does the same thing, but without an error. An “ArithmeticException” exception is thrown and the “getMessage()” and “printStackTrace()” method are called to display their return strings.

 

 

Example # 2:

/*******************************************************************

** This application is an illustration of how the Exceptional handing works and it shows

** the “throws”, “try” and  “catch” clauses plus the execution sequence of statements.

********************************************************************/

public class ExceptionHandling_1

{

final int   ZERO = 0;

 

public ExceptionHandling_1()

{

Method_1();

System.out.println("===========================================");

Method_2();

}

//**********************************************

float  CatchDivideByZeroMethod(int PassedInteger, int DivideByInteger)

throws ArithmeticException

{

System.out.println("***  The start of CatchZeroDivisionMethod ****");

if(0 == DivideByInteger)

    throw new ArithmeticException();

System.out.println("***   The end of CatchZeroDivisionMethod  ****");

return (PassedInteger / DivideByInteger);

}  // CatchZeroDivisionMethod

//**********************************************

void Method_1()

{

int           DivideByValue     = ZERO;

int           IntegerValue         = 20;

float       FloatValue              = -20;

 

System.out.println("***  The Start of Method_1   ****");

System.out.println("FloatValue = \t" + FloatValue);

try

{

System.out.println("***  Start of Method_1 Try Clause  ****");

FloatValue = CatchDivideByZeroMethod(IntegerValue, DivideByValue);

}

catch (ArithmeticException  MyArithmeticException)

{

System.out.println("*** Start of Method_1 Catch clause  ****");

System.out.println("***  can not divide by ZERO!!!! ****");

String ErrorMessage = MyArithmeticException.getMessage();

System.out.println("ErrorMessage = " + ErrorMessage);

MyArithmeticException.printStackTrace();

}

System.out.println("FloatValue = \t" + FloatValue);

System.out.println("***  The End of Method_1   ****");

} // Method_1

//**********************************************

void Method_2()

{

int           DivideByValue     = 2;

int           IntegerValue         = 50;

float       FloatValue              = -50;

 

System.out.println("***  The Start of Method_2   ****");

System.out.println("FloatValue = \t" + FloatValue);

try

{

System.out.println("***  Start of Method_2 Try Clause  ****");

FloatValue = CatchDivideByZeroMethod(IntegerValue, DivideByValue);

}

catch (ArithmeticException  MyArithmeticException)

{

System.out.println("*** Start of Method_2 Catch clause  ****");

System.out.println("***  can not divide by ZERO!!!! ****");

String ErrorMessage = MyArithmeticException.getMessage();

System.out.println("ErrorMessage = " + ErrorMessage);

MyArithmeticException.printStackTrace();

//      return;

}

System.out.println("FloatValue = \t" + FloatValue);

System.out.println("***  The End of Method_2   ****");

} // Method_2

//***************************************************

public static void main(String [] args)

{

ExceptionHandling_1  MyExceptionHandling_1            = new ExceptionHandling_1();

try

                {

                                                System.in.read();

                }

                                catch(Exception myException)

                {// do nothing

                                }

}

}

 

Output:

***  The Start of Method_1   ****

FloatValue =          -20.0

***  Start of Method_1 Try Clause  ****

***  The start of CatchZeroDivisionMethod   ****

*** Start of Method_1 Catch clause  ****

***  can not divide by ZERO!!!! ****

ErrorMessage = null

java.lang.ArithmeticException

        at ExceptionHandling_1.CatchDivideByZeroMethod (ExceptionHandling_1.java:22)

        at ExceptionHandling_1.Method_1 (ExceptionHandling_1.java:38)

        at ExceptionHandling_1.<init> (ExceptionHandling_1.java:13)

        at ExceptionHandling_1.main (ExceptionHandling_1.java:82)

FloatValue =                          -20.0

***  The End of Method_1   ****

===========================================

***  The Start of Method_2   ****

FloatValue =                          -50.0

***  Start of Method_2 Try Clause  ****

***  The start of CatchZeroDivisionMethod   ****

***   The end of CatchZeroDivisionMethod  ****

FloatValue =                          25.0

***  The End of Method_2   ****

 

Write a Java application that has a constructor and a method. The method should throw an exception and the constructor should handle it such an exception.  Make the constructor and the method write a print message to identify itself as it has been done in Example # 2.

 

 

“finally” Clause:

 

                The “finally” clause provides an exception handling and a cleanup code for the “try” clause.  The “finally” clause is optional and appears after the “try” and one or more “catch” clauses.  The code in the “finally” clause is executed once, regardless of how the code in the “try” clause executes.  There are two situations where the flow of execution takes place. 

 

The first is a normal execution, where the execution control reaches the end of “try” clause and then proceeds to the “finally” clause, which generally performs any necessary cleanup.  The “try” clause may have a “continue”, “break” or “return” statement, which would send the execution control some place in the program and out of the “try” clause.  The contents of the “finally” clause will be executed before the transfer of execution control leaves the “try” clause and ends in the new destination. 

 

The second situation is where an exception has occurred and the control flow is as follows:

 

1.        “try” clause  is executed and an exception takes place.

2.        Secondly, the proper “catch” clause is executed and finished.

3.        The “finally” clause is executed and before the flow the execution control is sent to any place else if “catch” clause has a “return”, “break” or “continue” statement.

4.        Once the “finally” is executed, the execution control is sent up to the nearest “catch” clause if there is no “return”, “break” or “continue” statement in the “finally” clause.

 

 

The “finally” clause can transfer execution control with a “return”, “break”, or “continue” statement or by throwing a new exception to be handled by the caller.

 

Test Case:

 

                The goal of Example # 3 is similar to Example # 2 with the addition of the “finally” clauses.  The code shows the sequence of execution where every method and “try”, “catch” and “finally” clauses print a message to indicate their execution.  The “ExecutionCount” counter is used to help with numbering the execution sequence.  The “finally” clause is executed regardless of the existence of an error or not.  The commented code in Example # 3 is to illustrate the compiler handling of code that will never be reached regardless of the outcome of the exception code.

 

 

try

{

               

return;

}

catch (ArithmeticException  MyArithmeticException)

{

               

return;

}

finally

{

               

}

….           // the code here will never be reached

 

 

Both “try” and “catch” clauses have a “return” statement and the code following the “finally” clause will never be executed.

 

 

Example # 3:

/***************************************************************

** This application is an illustration of how the Exceptional handing works and

** it shows the throws, “try”, “catch” and “finally” clauses plus the execution

** sequence of statements.

****************************************************************/

public class ExceptionWithFinally

{

final        int           ZERO                     = 0;

int           ExecutionCount    = 0;

 

public ExceptionWithFinally()

{

Method_1();

System.out.println("===========================================");

Method_2();

}

//**********************************************

float  CatchDivideByZeroMethod(int PassedInteger,  int DivideByInteger)

throws ArithmeticException

{

ExecutionCount++;

System.out.println(ExecutionCount

 + ")***  The start of CatchZeroDivisionMethod   ****");

if(0 == DivideByInteger)

   throw new ArithmeticException();

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***    The end of CatchZeroDivisionMethod   ****");

return (PassedInteger / DivideByInteger);

}  // CatchZeroDivisionMethod

//**********************************************

void Method_1()

{

int           DivideByValue     = ZERO;

int           IntegerValue         = 20;

float        FloatValue             = -20;

 

ExecutionCount++;

System.out.println(ExecutionCount  + ")***  The start of Method_1   ****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

try

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  Start of Method_1 Try Clause  ****");

FloatValue = CatchDivideByZeroMethod(IntegerValue, DivideByValue);

return;

}

catch (ArithmeticException  MyArithmeticException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_1 Catch clause  ****");

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  can not divide by ZERO!!!! ****");

return;

}

finally

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_1 finally clause  ****");

}

/*********

*****************************************************

** This portion of the code will not be reached and the compiler

** will not compile unless the code is commented.

*****************************************************

ExecutionCount++;

System.out.println(ExecutionCount    + "**** After Method_1 finally Block *****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

****************************************************************

*********/

} // Method_1

//**********************************************

void Method_2()

{

int           DivideByValue     = 2;

int           IntegerValue         = 50;

float        FloatValue   = -50;

 

ExecutionCount++;

System.out.println(ExecutionCount + ")***  The start of Method_2   ****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

try

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  Start of Method_2 Try Clause  ****");

FloatValue = CatchDivideByZeroMethod(IntegerValue,  DivideByValue);

}

catch (ArithmeticException  MyArithmeticException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_2 Catch clause  ****");

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  can not divide by ZERO!!!! ****");

return;

}

finally

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_2 finally clause  ****");

}

ExecutionCount++;

System.out.println(ExecutionCount + ")**** After Method_2 finally Block *****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

ExecutionCount++;

System.out.println(ExecutionCount + ")***  The End of Method_2   ****");

} // Method_2

//**************************************************

public static void main(String [] args)

{

ExceptionWithFinally  MyExceptionWithFinally           = new ExceptionWithFinally();

                try

                {

                                                System.in.read();

                }

                catch(Exception myException)

                {// do nothing

                }

}

}

 

Output:

1)***  The start of Method_1   ****

2)FloatValue =  -20.0

3)***  Start of Method_1 Try Clause  ****

4)***  The start of CatchZeroDivisionMethod   ****

5)*** Start of Method_1 Catch clause  ****

6)***  can not divide by ZERO!!!! ****

7)*** Start of Method_1 finally clause  ****

===========================================

8)***  The start of Method_2   ****

9)FloatValue =  -50.0

10)***  Start of Method_2 Try Clause  ****

11)***  The start of CatchZeroDivisionMethod   ****

12)***    The end of CatchZeroDivisionMethod   ****

13)*** Start of Method_2 finally clause  ****

14)**** After Method_2 finally Block *****

15)FloatValue =         25.0

16)***  The End of Method_2   ****

 

Write a Java application that has a constructor and a method. The method should throw an exception and the constructor should handle it such an exception.  The constructor should have the “try”, “catch” and “finally”.  Make the constructor, the method and each of the “try”, “catch” and “finally” blocks write a print message to identify itself as it has been done in Example # 3.

 

 

Where can the exception handling code be located?

 

                A method may throw one or more exceptions, the caller to that method must provide the “try”, “catch” and the optional “finally” clauses.   In the case of a sequence of methods calls, which method should provide the code handling?   For example, if a method A1 calls B2 where B2 calls C3, which calls D4 and D4 calls a method that throws an exception.  Figure # 2 is a rough representation of the calling sequence.   Which of these methods should provide the code handling, A1, B2, C3 or D4?  The answer is any of them or all of them may have the exception handling code, but there must be at least one method with the exception handling code.   How does the compiler check this rule?  The compiler will go through the callers looking for exception handling code until it gets to the system call and if it did not find the exception handling code, it will flag it and print a compiling error.  As for the execution of the application or applet, the Java interpreter once it encounters a throw of an exception, it will fold the stack for this method and return to the caller.  If the caller does not have the handling code, the same thing will happen and the folding of method’s stack continues until it reaches a method with the handling code, or ends up in the interpreter call, where the application will be terminated.

 

                                A1() à B2() à C3() à D4() à MethodThrowsException()

                                                                Figure # 2

 

Test Case:

 

                The goal in Example # 4 is to illustrate the folding of methods as the Java interpreter searches for exception handling code.  The “ExceptionHandling_2” class declares a number of methods and its constructor has the code for handling the exception which is thrown by the “CatchDivideByZeroMethod()” method.  The “ExceptionHandling_2” constructor executes two runs, the first is without any error and the second with an error.  The first run executes all the methods without any folding of methods.  Folding of method means terminating the method at the exception call and before reaching the end of method code.

 

***  The End of CatchZeroDivisionMethod   ****

****** End of Method_1  ************

****** End of CallMethod_1 ********

 

The end of each method message is printed in the first run.  In the second run, these end of message strings are missing, since the Java interpreter reached the throwing of the exception and then searches for the exception handling code.  If it does not find it in the current executing method, it folds the method without executing the rest of the method code.  It repeats such a process until it reaches the “ExceptionHandling_2” constructor and finds the exception handling code.  At this point, it runs the constructor normally and the constructor’s message string is printed as a normal run.  The “FloatValue” variable’s value does not change in the second run since the exception occurs during the division.

 

 

Example # 4:

/*******************************************************************

** This application is an illustration of how the Exception Handing works and it

** shows the throws, try, catch clauses plus the execution sequence of statements.

** The exception handling code can located in any of the caller.

********************************************************************/

public class ExceptionHandling_2

{

final int   ZERO = 0;

 

public ExceptionHandling_2()

{

int           DivideByValue     = 2;

int           IntegerValue         = 50;

float        FloatValue             = -50;

 

System.out.println("***  start of Constructor ExceptionHandling_2  ****");

try

{

System.out.println("***  Start of the First Constructor Try Clause  ****");

FloatValue = CallMethod_1(IntegerValue, DivideByValue);

}

catch (ArithmeticException  MyArithmeticException)

{

System.out.println("*** Start of The First Constructor Catch clause  ****");

System.out.println("***  can not divide by ZERO!!!! ****");

}

System.out.println("**** After the First Constructor catch clause “ +  “***********");

System.out.println("FloatValue = \t" + FloatValue);

System.out.println("\n============================================\n");

DivideByValue = ZERO;

IntegerValue = 20;

FloatValue   = -20;

try

{

System.out.println("***  Start of the 2nd Constructor Try Clause  ****");

FloatValue = CallMethod_1(IntegerValue, DivideByValue);

}

catch (ArithmeticException  MyArithmeticException)

{

System.out.println("*** Start of the 2nd Constructor Catch clause  ****");

System.out.println("***  can not divide by ZERO!!!! ****");

}

System.out.println("**** After the 2nd Constructor catch clause ***********");

System.out.println("FloatValue = \t" + FloatValue);

System.out.println("***  End of Constructor ExceptionHandling_2  ****");

}

//**********************************************

float  CatchDivideByZeroMethod(int PassedInteger, int DivideByInteger)

throws ArithmeticException

{

System.out.println("***  The start of CatchZeroDivisionMethod   ****");

if(0 == DivideByInteger)

   throw new ArithmeticException();

System.out.println("***  The End of CatchZeroDivisionMethod   ****");

return (PassedInteger / DivideByInteger);

}  // CatchZeroDivisionMethod

//**********************************************

float Method_1(int PassedInteger, int DivideByInteger)

{

float       FloatValue;

 

System.out.println("****** start of Method_1  ************");

FloatValue = CatchDivideByZeroMethod(PassedInteger, DivideByInteger);

System.out.println("****** End of Method_1  ************");

return(FloatValue);

} // Method_1

//**********************************************

float CallMethod_1(int PassedInteger, int DivideByInteger)

{

float       FloatValue   = -50;

 

System.out.println("****** Start of CallMethod_1 ********");

FloatValue = Method_1(PassedInteger, DivideByInteger);

System.out.println("****** End of CallMethod_1 ********");

return(FloatValue);

} // CallMethod_1

//***************************************************

public static void main(String [] args)

{

ExceptionHandling_2  MyExceptionHandling_2            = new ExceptionHandling_2();

                try

                {

                                System.in.read();

                }

                catch(Exception myException)

                {// do nothing

                }

  }

}

 

Output:

***  start of Constructor ExceptionHandling_2  ****

***  Start of the First Constructor Try Clause  ****

****** Start of CallMethod_1 ********

****** start of Method_1  ************

***  The start of CatchZeroDivisionMethod   ****

***  The End of CatchZeroDivisionMethod   ****

****** End of Method_1  ************

****** End of CallMethod_1 ********

**** After the First Constructor catch clause ***********

FloatValue =    25.0

 

====================================================

 

***  Start of the 2nd Constructor Try Clause  ****

****** Start of CallMethod_1 ********

****** start of Method_1  ************

***  The start of CatchZeroDivisionMethod   ****

*** Start of the 2nd Constructor Catch clause  ****

***  can not divide by ZERO!!!! ****

**** After the 2nd Constructor catch clause ***********

FloatValue =    -20.0

***  End of Constructor ExceptionHandling_2  ****

 

 

Rewrite Example # 4 with, but remove “Method_1()” from the class and trace the result of your Java application.

               

 

Multiple Exception handling:

 

                Multiple Exception handling is divided into multiple throws and/or nested throws.   A method or a class can throw multiple exceptions, and within the “try”, “catch” or “finally” clauses a new nested exception’s throws can be made.

 

Test Case:

 

                Example # 5 code is an attempt to show a method that throws multiple exceptions.  Example # 5 declares the “MultipleExceptions” class, which declares the “Method_1()” and the “MultiExceptionMethod()” methods.  The “MultiExceptionMethod()” method throws a number of exceptions, and “Method_1()” calls the “MultiExceptionMethod()” method and passes to it an integer parameter that goes throw an “if” statement where a different exception is selected.  The first run of the “Method_1()” method does not execute any exception and only the “try” and “finally” clauses are executed.  With this run the “FloatValue” value will change from –20 to 10 and the “MultiExceptionMethod()” is executed without any exception handling folding of method.  This means that none of the exceptions is thrown and the “MultiExceptionMethod()” method reaches its last statement and returns its argument :

 

“return (PassedInteger)”;

 

Basically, the following code is executed and its output is as shown below the code:

 

try

{

FloatValue = MultiExceptionMethod(IntegerValue);

}

 

                output:

8)FloatValue =  10.0

 

 

The following three runs of the “MultiExceptionMethod()” method throw different exceptions and different “catch” clause is executed.  The “FloatValue” never changes from –20 since the “MultiExceptionMethod()” method never reaches its end due to its folding at the throws of the exception. The execution control is transferred to “Method_1” to handle the exception before the “MultiExceptionMethod()” reaches its end.  The “try” and “finally” clauses are executed with “MultiExceptionMethod()” method runs, but different “catch” clause is executed depending on which exception is thrown.  The output of Example # 5 shows the execution sequence and the value of “FloatValue”.  The “FloatValue” is used to illustrate the folding of methods when an exception takes place.

 

 

Example # 5:

/*******************************************************************

** This application is an illustration of Multiple Exceptions

********************************************************************/

import java.io.*;

import java.lang.*;

 

public class MultipleExceptions

{

int                           ExecutionCount    = 0;

 

public MultipleExceptions()

{

Method_1(10);

promptForCarriageReturn();

System.out.println("===========================================");

Method_1(2);

promptForCarriageReturn();

System.out.println("===========================================");

Method_1(1);

promptForCarriageReturn();

System.out.println("===========================================");

Method_1(0);

}

//**********************************************

float  MultiExceptionMethod(int PassedInteger)

        throws            rithmeticException,

IOException,

IndexOutOfBoundsException

{

ExecutionCount++;

System.out.println(ExecutionCount+ ")***  The start of MultiExceptionMethod   ****");

if(0 == PassedInteger)

  throw new ArithmeticException();

else

   if(1 == PassedInteger)

     throw new IOException();

  else

    if(2 == PassedInteger)

      throw new IndexOutOfBoundsException();

ExecutionCount++;

System.out.println(ExecutionCount+ ")***  End of MultiExceptionMethod ****");

return (PassedInteger);

}  // MultiExceptionMethod

//**********************************************

void Method_1(int IntegerValue)

{

float       FloatValue   = -20;

 

ExecutionCount++;

System.out.println(ExecutionCount  + ")***  The start of Method_1   ****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

try

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  Start of Method_1 Try Clause  ****");

FloatValue = MultiExceptionMethod(IntegerValue);

}

catch (ArithmeticException  MyArithmeticException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of ArithmeticException catch Clause  ****");

}

catch (IOException  MyIOException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of IOException catch Clause  ****");

}

catch (IndexOutOfBoundsException  MyIndexOutOfBoundsException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of IndexOutOfBoundsException catch + “Clause  ****");

}

finally

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_1 finally clause  ****");

}

ExecutionCount++;

System.out.println(ExecutionCount+ ")**** After Method_1 finally Block *****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

ExecutionCount++;

System.out.println(ExecutionCount + ")***  The End of Method_1   ****");

} // Method_1

//****************************************************

void promptForCarriageReturn()

{

System.out.println("Press Enter key to continue");

                try

                                {

                int readKey = System.in.read();

                                                if(   ('\r' == readKey)

                                   || ('\n' == readKey)

                                                  )

                                                 System.in.read();

                }

                catch(Exception myException)

                                {// do nothing

                }

}

//****************************************************

public static void main(String [] args)

{

MultipleExceptions  MyMultipleExceptions   = new MultipleExceptions();

                try

                {

                                                System.in.read();

                }

                                catch(Exception myException)

                {// do nothing

                                }

}

}

 

Output:

1)***  The start of Method_1   ****

2)FloatValue =  -20.0

3)***  Start of Method_1 Try Clause  ****

4)***  The start of MultiExceptionMethod   ****

5)***  End of MultiExceptionMethod ****

6)*** Start of Method_1 finally clause  ****

7)**** After Method_1 finally Block *****

8)FloatValue =  10.0

9)***  The End of Method_1   ****

Press Enter key to continue

 

===========================================

10)***  The start of Method_1   ****

11)FloatValue =         -20.0

12)***  Start of Method_1 Try Clause  ****

13)***  The start of MultiExceptionMethod   ****

14)*** Start of IndexOutOfBoundsException catch Clause  ****

15)*** Start of Method_1 finally clause  ****

16)**** After Method_1 finally Block *****

17)FloatValue =         -20.0

18)***  The End of Method_1   ****

Press Enter key to continue

 

===========================================

19)***  The start of Method_1   ****

20)FloatValue =         -20.0

21)***  Start of Method_1 Try Clause  ****

22)***  The start of MultiExceptionMethod   ****

23)*** Start of IOException catch Clause  ****

24)*** Start of Method_1 finally clause  ****

25)**** After Method_1 finally Block *****

26)FloatValue =         -20.0

27)***  The End of Method_1   ****

Press Enter key to continue

 

===========================================

28)***  The start of Method_1   ****

29)FloatValue =         -20.0

30)***  Start of Method_1 Try Clause  ****

31)***  The start of MultiExceptionMethod   ****

32)*** Start of ArithmeticException catch Clause  ****

33)*** Start of Method_1 finally clause  ****

34)**** After Method_1 finally Block *****

35)FloatValue =         -20.0

36)***  The End of Method_1   ****

 

Write a Java application that has a constructor and a method. The method should throw three different exceptions and the constructor should handle all of them.  The constructor should have the “try”, “catch” and “finally” ( the “finally” is optional).  Make the constructor, the method and each of the “try”, “catch” and “finally” blocks write a print message to identify itself as it has been done in Example # 5.

 

 

“Throws” and “Throw”:

 

                “Throws” and “Throw” are two distinct reserve words in Java.  The first is “Throws” and is used in a method declaration to list the exceptions that the method may throw. The example in the following code is an illustration where “MultiExceptionMethod” throws three types of exceptions.  “MultiExceptionMethod()” method has to declare three exception instances for each of the exceptions thrown.

 

float  MultiExceptionMethod(int PassedInteger)

throws    ArithmeticException,           // 1

               IOException,                          // 2

               IndexOutOfBoundsException             // 3

{

if(0 == PassedInteger)

      throw new ArithmeticException();              // 1

else

      if(1 == PassedInteger)

        throw new IOException();                           // 2

     else

        if(2 == PassedInteger)

          throw new IndexOutOfBoundsException();          // 3

}

 

 

The second is “Throw” statement which signals an exception condition has occurred by throwing an exception of the proper type.   “Throw” statement will stop the execution and transfer the execution control to the proper “catch” clause, which the caller must have.   The example in next code segment is an illustration of “catch” and “finally” clauses, where each has thrown a different type of exception.

 

try

{

               

FloatValue = ExceptionMethod(IntegerValue);

}

catch (ArithmeticException  MyArithmeticException)

{

               

throw new IndexOutOfBoundsException();

}

finally

{

               

throw new IOException();

// it may not return back from the caller!

}

 

 

The above code has the “catch” and “finally” clauses and each throws an exception.  The important thing to remember is once the transfer of execution is sent out of the exception “catch” clause, it may not be returned to the “catch” clause.  This is the reason the “finally” clause is executed before the transfer of execution control takes place.  If there is an exception thrown in the “finally” clause, the execution control will be transferred to the caller and the remaining statements in the “catch” clause will not be executed.  Looking at the above code, the “throw new IndexOutOfBoundsException();” statement and all the statements listed after it in the “catch” clause will not be executed.

 

 

Test Case:

 

                Example # 6 is an attempt to show that the execution control may not return to the “try” or the “catch” clauses, but the “finally” clause will be executed regardless.  Example # 6 declares the “ExceptionThrowsException” class, which declares the “Method_1()” and the “ExceptionMethod()” methods.  The “finally” clause of  “Method_1()” method throws an exception and the execution control is sent to the constructor and never returns back to any of the methods.  The following is a clip of the output showing the execution sequence:

 

 

8)*** Start of Method_1 finally clause  ****

9)*** Start of IOException Constructor catch Clause  ****

10)*** The end of ExceptionThrowsException Constructor****

 

The application is terminated at the constructor and none of the methods reached their normal end of executions.

 

 

Example # 6:

/*******************************************************************

** This application is an illustration of an Exception throws an Exception

********************************************************************/

import java.io.*;

import java.lang.*;

 

public class ExceptionThrowsException

{

int         ExecutionCount = 0;

 

public ExceptionThrowsException()

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** The start of ExceptionThrowsException Constructor****");

try

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  Start of Try Constructor Clause  ****");

Method_1(0);

}

catch (IOException  MyIOException)

{

ExecutionCount++;

System.out.println(ExecutionCount

 + ")*** Start of IOException Constructor catch Clause ****");

}

catch (IndexOutOfBoundsException  MyIndexOutOfBoundsException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of IndexOutOfBoundsException Constructor catch Clause  ****");

}

ExecutionCount++;

System.out.println(ExecutionCount

               + ")*** The end of ExceptionThrowsException Constructor****");

}

//**********************************************

float ExceptionMethod(int PassedInteger)

throws                    ArithmeticException

{

ExecutionCount++;

System.out.println(ExecutionCount + ")***  The start of ExceptionMethod   ****");

if(0 == PassedInteger)

   throw new ArithmeticException();

ExecutionCount++;

System.out.println(ExecutionCount + ")***  End of ExceptionMethod ****");

return (PassedInteger);

}  // ExceptionMethod

//**********************************************

void Method_1(int IntegerValue)

throws                    IOException,

IndexOutOfBoundsException

{

float       FloatValue   = -20;

 

ExecutionCount++;

System.out.println(ExecutionCount + ")***  The start of Method_1   ****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

try

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")***  Start of Method_1 Try Clause  ****");

FloatValue = ExceptionMethod(IntegerValue);

}

catch (ArithmeticException  MyArithmeticException)

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of ArithmeticException catch Clause  ****");

throw new IndexOutOfBoundsException();

}

finally

{

ExecutionCount++;

System.out.println(ExecutionCount

+ ")*** Start of Method_1 finally clause  ****");

throw new IOException();

}

/*************

** Statments not reachable error and we have to comment them

ExecutionCount++;

System.out.println(ExecutionCount + "**** After Method_1 finally Block *****");

ExecutionCount++;

System.out.println(ExecutionCount + ")FloatValue = \t" + FloatValue);

****/

} // Method_1

//***************************************************

public static void main(String [] args)

{

ExceptionThrowsException  MyExceptionThrowsException

 = new ExceptionThrowsException();

                try

                                {

                                System.in.read();

                                }

                catch(Exception myException)

                                {// do nothing

                }

}

}

 

Output:

1)*** The start of ExceptionThrowsException Constructor****

2)***  Start of Try Constructor Clause  ****

3)***  The start of Method_1   ****

4)FloatValue =  -20.0

5)***  Start of Method_1 Try Clause  ****

6)***  The start of ExceptionMethod   ****

7)*** Start of ArithmeticException catch Clause  ****

8)*** Start of Method_1 finally clause  ****

9)*** Start of IOException Constructor catch Clause  ****

10)*** The end of ExceptionThrowsException Constructor****

 

Write a Java application that has a constructor and two methods. The methods should throw different exceptions.  The constructor should handle call one of the method, which in turn calls the second method. Write the proper code to hand these nesting of exceptions, as it has been done in Example # 6. Make the constructor, the methods and each of the “try” and “catch” blocks write a print message to identify itself as it has been done in Example # 6.