472,368 Members | 2,630 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,368 developers and data experts.

An Introduction to Exceptions - Ch. 2

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.
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. }
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. }
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.     }
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!

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. }
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 5189

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

Similar topics

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...
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...
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...
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,...
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...
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...
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...
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...
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
by: Carina712 | last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
by: BLUEPANDA | last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
by: Rahul1995seven | last post by:
Introduction: In the realm of programming languages, Python has emerged as a powerhouse. With its simplicity, versatility, and robustness, Python has gained popularity among beginners and experts...
by: Ricardo de Mila | last post by:
Dear people, good afternoon... I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control. Than I need to discover what...
by: Johno34 | last post by:
I have this click event on my form. It speaks to a Datasheet Subform Private Sub Command260_Click() Dim r As DAO.Recordset Set r = Form_frmABCD.Form.RecordsetClone r.MoveFirst Do If...
by: jack2019x | last post by:
hello, Is there code or static lib for hook swapchain present? I wanna hook dxgi swapchain present for dx11 and dx9.

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.