Creating User-defined Exceptions


The Finally Clause

Home  »  Java  »  Advance Java  »  Java Exception Handling  »  The Finally Clause


Suppose there are some action in the code that must be performed no matter what happens, that is, whather an exception is thrown or not. This is usually to free some external resource after acquiring it, to close a file after opening it, or something similar. While one could put that action both inside a catch block and outside it, that would be duplicating that same code in two different places.

Instead, one could put a copy of the code inside a special optional part of the try...cath block called finally.

Example:

The following example shows how a try...catch...finally block is structured.



The finally statement is actually useful outside exceptions, one can use it to execute cleanup code after a return, a break, or a continue inside loop.

The followning example shows how a finally statement can be used inside a method, to print the contents of the initialized array through a user-defined method.



C:\>jdk1.4\bin>javac Finally.java
C:\>jdk1.4\bin>java FinallyClause

The try...finally block causes an unusual thing to happen when the return statement is encountered. As the return statement is within the try...finally block, the statement within the finally block are executed no matter how the try block is exited. The "last number read" text always is displayed.


Download Complete Program

  -  



Java Exception Handling


Catching Java Exceptions Catching a RunTime Exception
Handling Multiple Exceptions The finally Clause
Creating User-defined Exceptions



Handling Multiple Exceptions

Home  »  Java  »  Advance Java  »  Java Exception Handling  »  Handling Multiple Exceptions


The following example shows how to handle multiple exceptions. For example, if the user enters a zero in the second text field and Java tries to divide the first number by the zero, an ArithmeticException exception is raised. So, what if there are two exceptions to deal with i.e: the NumberFormatException and the ArithmeticException. This means there are multiple exceptions to be handled.

The good news is that there is no limit to the number of catch blocks. The catch blocks can be generated for any exception that the program generates.

The below program show how to handle multiple exceptions in java programming.





C:\>jdk1.4\bin>javac HandMulExcepApp.java
C:\>jdk1.4\bin>appletviewer HandMulExcepApp.html

The actionPerformed() in the above code uses two catch program blocks, one each for the NumberFormatException and ArithmeticException exceptions.

The ArithmeticException is raised when a number is divided by zero. In above Diagram the first number i.e. 10 is divided by the second number i.e. 0. This gives a message i.e. "Division by 0, this is NOT ALLOWED in Math".


Download Complete Program

  -    -  HTML File



Java Exception Handling


Catching Java Exceptions Catching a RunTime Exception
Handling Multiple Exceptions The finally Clause
Creating User-defined Exceptions




Catching a RunTime Exception

Home  »  Java  »  Advance Java  »  Java Exception Handling  »  Catching a RunTime Exception


The following example is an advancement of the above example. This example shows how to handle exceptions. For example, the following code catches the NumberFormatException in case leaves either of the text boxes empty or enters an invalid value such as a String.





C:\>jdk1.4\bin>javac RunTimeExcepApp.java
C:\>jdk1.4\bin>appletviewer RunTimeExcepApp.html


The actionPerformed() uses the try and the catch blocks to handle the NumberFormatException. The below Diagram shows what happens when the user leaves the text fields blank or enters an invalid numerical value. When the program gets to the first call to String.valueOf(). Java generates the NumberFormatException exception, which causes program execution to jump to the catch block. In the catch block, the program sets the display string to "Invalid Number". This is done by setting the text of the label to "Invalid Number".


Invalid numerical value being entered


Download Complete Program

  -    -  HTML File



Java Exception Handling


Catching Java Exceptions Catching a RunTime Exception
Handling Multiple Exceptions The finally Clause
Creating User-defined Exceptions



Java Exception Handling

Home  »    Java   »    Advance Java  »  Exception Handling

An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

Exceptions can be thrown by the system or explicitly thrown by the program. Exceptions include errors that could be fatal to a program, and may also include other unusual situations. By managing exceptions, one can manage errors and possibly work around them.

Exceptions in Java are actual objects. They are instances of classes that are inherited from the class Throwable. An instance of a Throwable class is created when an exception is thrown.

The below diagram shows a partial class hierarchy for exceptions.



Throwable has two subclass Error and Exception class. Instances of Error class are internal errors in Java runtime environment( the virtual machine). These error are rare and are usually fatal.

Suvclass of Exception fall into two general groups:

  1. Runtime exceptions (subclasses of the class RuntimeException) such as ArrayIndexOutofBounds, SecurityException, or NullPointerException.
  2. Other exceptions such as EOFException and NullPointerException.





Catching Java Exceptions

The following two steps need to be performed to trap an exception:

  1. Protect the code that contains the method that might throw an exception inside a try block.
  2. Test for and deal with an exception inside a catch block.


What try and catch effectively means is "try" the code that might cause an exception. If it executes, go on with the program. If it does not execute catch the exception and deal with it".

The catch block should immediately follow the try block.

Example
The following algorithm can explain the try and catch method.



The above example explains the algorithm of opening a file. The opening of the file could potentially throw an exception. To handle this exception, the code is enclosed inside a try block.

As the try block is likely to throw any file related error, an associated catch block traps a file related exception.

The following example is an applet called ExecpApp with two text fileds, When a number is entered in each of the text fields and the Enter key is pressed, the program divides the first number by the second and display the result (dropping any remainder). the following example does not contain any exception-handling code.




C:\>jdk1.4\bin>javac ExcepApp.java
C:\>jdk1.4\bin>appletviewer ExcepApp.html



"Output of ExcepApp.class"

Incase the user presses the Entery key when either of the text boxes are empty or enteres an invalid numerical value, then Java throws a NumberFormatException.





Incase of Division by zero, refer the below diagram for th ArithemeticException raised.




"Division by zero"



Arithmetic Exception raised incase of division by zero

Incase of a valid number being entered, the result after the division of numbers is shown in below diagram.
















Incase of a valid number entered













































































Catching Java Exceptions Catching a RunTime Exception
Handling Multiple Exceptions The finally Clause
Creating User-defined Exceptions



<< Previous Topic
Next Topic >>