Home arrow Java & J2EE arrow Page 3 - Exception Handling Techniques in Java

More Exception Handling Examples - Java

Exception handling is one of those programming techniques that beginners often neglect to implement. However, when they end up working on a large project on which dozens of other colleagues are working, they find that you just can’t afford to be superficial. Throughout this article we’re going to cover exceptions, explain what they are, how to work with them, and why they are important—ultimately, how to handle them.

TABLE OF CONTENTS:
  1. Exception Handling Techniques in Java
  2. Exception Handling
  3. More Exception Handling Examples
  4. Final Thoughts
By: Barzan "Tony" Antal
Rating: starstarstarstarstar / 30
March 11, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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 & J2EE Articles          >>> More By Barzan "Tony" Antal
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

JAVA & J2EE ARTICLES

- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: