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:
- Throw the Exception further (pass it on to some other place)
- Catch the Exception and cope with it
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
- public void calculate(double a, double b, char func) throws Exception
- {
- double result;
- switch(func)
- {
- case '+' : result = add(a,b); break;
- case '-' : result = sub(a,b); break;
- case '*' : result = mul(a,b); break;
- case '/' : result = div(a,b); break;
- default : result = 0;
- }
- System.out.println(a + " " + func + " " + b + " = " + result);
- }
- public double add(double a, double b)
- {
- return a+b;
- }
- public double sub(double a, double b)
- {
- return a-b;
- }
- public double mul(double a, double b)
- {
- return a*b;
- }
- public double div(double a, double b) throws Exception
- {
- if (b==0) throw new Exception();
- return a/b;
- }
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
- try
- {
- calculate(6.,0.,'/');
- }
- catch(Exception e)
- {
- System.out.println("ERROR: You can't divide by zero!");
- }
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
- public static void Thrower(boolean x) throws NullPointerException, ArrayIndexOutOfBoundsException
- {
- if(x) throw new NullPointerException();
- else throw new ArrayIndexOutOfBoundsException();
- }
- public static void main(String[] args) {
- try
- {
- Thrower(false);
- }
- catch(NullPointerException npe)
- {
- System.out.println("Caught a NullPointerException");
- }
- catch(ArrayIndexOutOfBoundsException aioobe)
- {
- System.out.println("Caught an ArrayIndexOutOfBoundsException ");
- }
- }
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
- ...
- catch(Exception e)
- {
- e.printStackTrace();
- }
Expand|Select|Wrap|Line Numbers
- java.lang.NullPointerException
- at exceptionArticle.Division.Thrower(Division.java:63)
- at exceptionArticle.Division.main(Division.java:14)