473,387 Members | 1,549 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,387 developers and data experts.

An Introduction to Exceptions - Ch. 2

RedSon
5,000 Expert 4TB
Chapter 2: How to handle Exceptions
When you call a program, sometimes you get a message about an Unhandled exception type. This means, that something throws (or might throw) an Exception, but the compiler doesn't know, what to do then.

You can deal with this in two different ways:
  1. Throw the Exception further (pass it on to some other place)
  2. Catch the Exception and cope with it
Depending on what you want to do, when an Exception occurs, one or the other Method might be the best choice.

If you just want to throw the Exception further, it's enough to add throws Exception to any function, which should pass it on. That's the easy way and often, it is enough.
Example:
Expand|Select|Wrap|Line Numbers
  1. public void calculate(double a, double b, char func) throws Exception
  2. {
  3.     double result;
  4.     switch(func)
  5.     {
  6.     case '+' : result = add(a,b); break;
  7.     case '-' : result = sub(a,b); break;
  8.     case '*' : result = mul(a,b); break;
  9.     case '/' : result = div(a,b); break;
  10.     default  : result = 0;
  11.     }
  12.     System.out.println(a + " " + func + " " + b + " = " + result);
  13. }
  14. public double add(double a, double b)
  15. {
  16.     return a+b;
  17. }
  18. public double sub(double a, double b)
  19. {
  20.     return a-b;
  21. }
  22. public double mul(double a, double b)
  23. {
  24.     return a*b;
  25. }
  26. public double div(double a, double b) throws Exception
  27. {
  28.     if (b==0) throw new Exception();
  29.     return a/b;
  30. }
  31.  
This will try to calculate the result of a call like calculate(2.,3.,'+') or calculate(2.,3.,'/'). However, theese calles will again cause an Unhandled exception type Exception message by the compiler.

At some point the exception has to be caught and delt with. Exactly this is done by the try-catch-structure:
Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.     calculate(6.,0.,'/');
  4. }
  5. catch(Exception e)
  6. {
  7.     System.out.println("ERROR: You can't divide by zero!");
  8. }
  9.  
So, the program tries to calculate the result and can catch an Exception and react to it.

Now, there are different types of Exceptions and you might want to react to them in different ways. The easiest way of demonstrating this, is the following program:
Expand|Select|Wrap|Line Numbers
  1. public static void Thrower(boolean x) throws NullPointerException, ArrayIndexOutOfBoundsException 
  2.     {
  3.         if(x) throw new NullPointerException();
  4.         else throw new ArrayIndexOutOfBoundsException();
  5.     }
  6. public static void main(String[] args) {
  7.         try
  8.         {
  9.             Thrower(false);
  10.         }
  11.         catch(NullPointerException npe)
  12.         {
  13.             System.out.println("Caught a NullPointerException");
  14.         }
  15.         catch(ArrayIndexOutOfBoundsException  aioobe)
  16.         {
  17.             System.out.println("Caught an ArrayIndexOutOfBoundsException ");
  18.         }
  19.     }
  20.  
WARNING: You should NOT write a program like this in general. A function should NOT do nothing but throw Exceptions. That can create very ugly code!

Tip:
If at some point you get an Exception and want to know more about it (like where it comes from), there is e very easy method of doing so:
Expand|Select|Wrap|Line Numbers
  1. ...
  2. catch(Exception e)
  3. {
  4.     e.printStackTrace();
  5. }
  6.  
It could give you something like this:
Expand|Select|Wrap|Line Numbers
  1. java.lang.NullPointerException
  2.     at exceptionArticle.Division.Thrower(Division.java:63)
  3.     at exceptionArticle.Division.main(Division.java:14)
Back to chapter 1 or Continue to chapter 3
Dec 18 '07 #1
0 5307

Sign in to post your reply or Sign up for a free account.

Similar topics

14
by: Cletis Tout | last post by:
http://www.codeproject.com/cpnet/introtomono1.asp Introduction to Mono - Your first Mono app By Brian Delahunty The first in a series of articles about Mono. This article explains how to...
14
by: Alf P. Steinbach | last post by:
Not yet perfect, but: http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01.pdf http://home.no.net/dubjai/win32cpptut/special/pointers/ch_01_examples.zip To access the table of...
12
by: Xah Lee | last post by:
Of Interest: Introduction to 3D Graphics Programing http://xahlee.org/3d/index.html Currently, this introduction introduces you to the graphics format of Mathematica, and two Java Applet...
2
by: Jeroen | last post by:
We are experiencing a tuff-to-debug problem ever since we introduced a WebBrowser control into our failry large application. I'm not sure if the problem description below contains enough details,...
5
by: r035198x | last post by:
Setting up. Getting started To get started with java, one must download and install a version of Sun's JDK (Java Development Kit). The newest release at the time of writting this article is...
0
by: r035198x | last post by:
Inheritance We have already covered one important concept of object-oriented programming, namely encapsulation, in the previous article. These articles are not articles on object oriented...
0
Nepomuk
by: Nepomuk | last post by:
Chapter 1: What is an Exception? Imagine, you want to write a program for calculating. You start, it works fine, you can add, subtract, multiply and divide. Then there's a question: What about the...
0
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.