Java
  Home arrow Java arrow Page 3 - Exception Handling Techniques in Java
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
JAVA

Exception Handling Techniques in Java
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 8
    2009-03-11


    Table of Contents:
  • Exception Handling Techniques in Java
  • Exception Handling
  • More Exception Handling Examples
  • Final Thoughts

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Exception Handling Techniques in Java - More Exception Handling Examples
    ( Page 3 of 4 )

    Beginners often struggle with non-matching data types. Frequently they cause problems, such as the occurrence of non-numeric types during addition. In the following code snippet we will present a workaround to this with exception handling. Check out this website for the complete list of built-in Exception types. Right now, we're going to deal with NumberFormatException occurrences.

    public static void main (String args[]) {

    double sum = 0;

    for (int i = 0; i < args.length; ++i)

    try {

    sum += Double.parseDouble (args[i]);

    }

    catch (NumberFormatException e){

    System.out.println(args[i] + " non-numeric data on");

    }

    System.out.println("Total sum: " + sum);

    }

     

    As you can see, it works with command line arguments, and once a non-numeric argument is reached, it is just written to the standard system out, specifying what's wrong. But the program goes on, since the try block is within a for loop. Otherwise, without proper exception handling, the program would be terminated. This way the sum is still calculated and printed out at the end.

    Let's present another example. Here we are going to build our own exception class that extends the parent Exception class. The application will simulate the way a stack mechanism works with exception handling, throwing and dealing with exceptions such as Stack is full (and you want to add more elements into the stack) or Stack is empty (and you want to pop elements from the stack). Check it out.

    public class StackException extends Exception {

    public StackException (String text) {

    super (text);

    }

    }

     

    Now let's create the Stack class itself. Pay attention to the push and pop methods. They are throwing the StackException type of exception, and this is introduced within the method signature. Moreover, there's an if condition, and the exception is thrown if it's satisfied. Otherwise, everything just happens smoothly.

     

    public class Stack {

    private final int SIZE = 100;

    private Object st[];

    private int size;

    private int sp;

     

    public Stack (int size) {

    if (size < MAXSIZE)

    this.size = size;

    else

    this.size = MAXSIZE;

    this.st = new Object [size];

    this.sp = -1;

    }

     

    public void push (Object o) throws StackException {

    if (sp == this.size - 1)

    throw new StackException ("Stack is full");

    this.st [++this.sp] = o;

    }

     

    public Object pop () throws StackException {

    if (sp == -1)

    throw new StackException ("Stack is empty");

    Object o = this.st [this.sp];

    this.sp--;

    return o;

    }

     

    public boolean isEmpty() {

    return this.sp == -1;

    }

    }

    All right, now it's time to write the Main class along with the main method. In this part, pay extra attention to the try-catch constructs. There are two kinds of exceptions to be caught (either the stack is empty or full). You'll easily figure out their role.

    public class Main {

    public static void main (String args[]) {

    Stack s = new Stack (10);

    for (int i = 0; i <= 10; ++i)

    try {

    s.push (new Integer(i));

    }

    catch (StackException e) {

    System.out.println (e);

    }

    while (! s.isEmpty() ) {

    try {

    System.out.println( (Integer)(s.pop()) );

    }

    catch (StackException e) {

    System.out.println(e);

    }

    }

    }

    }

     

    Of course, here's the attached output as well. As you can see, the first line that is printed out is the exception, since we're planning to fill the stack with 11 elements (consider: the for loop begins from 0 and goes up to 10 but also includes that value, this is a total of 11 elements), thus, the exception is thrown. Then it is also dealt with. The other exception doesn't get thrown, since the while loop goes until isEmpty is false.

     

    Stack is full

    9

    8

    7

    6

    5

    4

    3

    2

    1

    0

     

    Play around with the above code for a little while. Try to pop another element. And don't get surprised if the exception is thrown but also dealt with right away. That is the real power of exception handling, as you can see. So that's it for now.



     
     
    >>> More Java Articles          >>> More By Barzan "Tony" Antal
     

       

    JAVA ARTICLES

    - Exception Handling Techniques in Java
    - More About Multithreading in Java
    - The Basics of Multiple Threads in Java
    - Data Access Using Spring Framework JDBC
    - New Object Initialization in Java
    - Adding Images With iTextSharp
    - Adding Columns With iTextSharp
    - Creating Simple PDF Files With iTextSharp
    - The Spring Framework: Understanding IoC
    - Introducing the Spring Framework
    - Java Classes
    - Completing the Syntactic Comparison of Java ...
    - Syntactic Comparison of Java and C/C++
    - Java Statements
    - Conditionals, Expressions and Other Java Ope...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 5 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek