473,469 Members | 1,633 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

An Introduction to Exceptions - Ch. 2

RedSon
5,000 Recognized Expert Expert
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 5313

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: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
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...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...

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.