Welcome to Dream.In.Code
Click Here
Getting Java Help is Easy!

Join 118,660 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 863 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Exceptions Advanced - Customizing

 
Reply to this topicStart new topic

> Exceptions Advanced - Customizing, Examples and Explanation of how to create and customize your Exception

William_Wilson
Group Icon



post 5 Jan, 2007 - 07:16 PM
Post #1


Java Exception Handling - Customizing

You should have a good deal of knowledge on the subject of Exceptions, where they are generated, your options in dealing with them, as well as the classes and subclasses involved in handling your Exceptions.
We will now use all of that information to start creating our own Exception Handlers which will extend Java's built in Exceptions and take advantage of their methods, as well as adding our own.

I will start with how to design the code segments, these are also available in the code snippets section I also used a similar version in the throwing tutorial, but i will better explain how they work, why they work and how to use them:

1) determine the Exception you wish to handle
2) determine an appropriate Exception class to extend, if there is none, you can write that too, or just extend Exception.

The testing code is very similar to the code from the last tutorial, just a simple name switch to the Exception we will be calling.
Tester Class ExceptionTester:
CODE

public class ExceptionTester {
     private static int quotient(int numerator, int denominator) throws DivideByZeroException {
          if(denominator == 0)
               throw new DivideByZeroException();
          return(numerator / denominator);
     }

     public static void main(String args[]) {
          int number1=0, number2=0, result=0;
          try {
             number1 = 1;
             number2 = 0;
             result = quotient(number1,number2);
             System.out.print(number2 + " goes into " + number1);
             System.out.println(" this many times: " + result);
          }
          catch (Exception e) {
             System.out.println(e);
             System.out.println("An Exception occured");
          }
     }
}


It is not that difficult to create your own exceptions once you understand how to use them. It is simply a matter of a few lines of code, written in the correct order.

Here is the example I spoke of, I chose to write a Divide by Zero Exception, which will extend ArithmeticException, since it is an Arithmetic operation gone wrong. Although the existing Exception can determine if the operation was a divide by zero I will use this as my first example anyway.

Exception Class DivideByZeroException:
CODE

public class DivideByZeroException extends ArithmeticException {
    public DivideByZeroException() {
          super("Attempted to divide by zero!");
    }
}


Upon generating the Exception, it prints the text you send to super, which in this case is ArithmeticException, similar to throwing, but in this case the name of the exception is your declared name DivideByZeroException.

Other than that there is little more to know about writting your own exceptions. You can however add methods, which is uncommon, or override the methods provided to get your own meaning from them.

The following code overrides the getMethod() method:
CODE

public class exceptions {
    public static class DivideByZeroException extends ArithmeticException {
        public DivideByZeroException() {
              super("Attempted to divide by zero!");
        }
        public String getMessage(){
            return "an overriden getMessage() method!";
        }
    }
     private static int quotient(int numerator, int denominator) throws DivideByZeroException {
          if(denominator == 0)
               throw new DivideByZeroException();
          return(numerator / denominator);
     }

     public static void main(String args[]) {
          int number1=2, number2=0, result=0;
          try {
             result = quotient(number1,number2);
             System.out.print(number2 + " goes into " + number1);
             System.out.println(" this many times: " + result);
          }
          catch (Exception e) {
             System.out.println(e.getMessage());
             System.out.println("An Exception occured");
          }
     }
}

Output:
QUOTE

an overriden getMessage() method!
An Exception occured


Perhaps override the getStackTrace() method to return in the trace only the first element:

CODE

public class exceptions {
    public static class DivideByZeroException extends ArithmeticException {
        public DivideByZeroException() {
              super("Attempted to divide by zero!");
        }
        public String getMessage(){
            return "an overriden getMessage() method!";
        }
        public StackTraceElement[] getStackTrace(){
            StackTraceElement[] ste = super.getStackTrace();
            StackTraceElement[] s = new StackTraceElement[1];
            s[0] = ste[ste.length-1];
            return s;
        }
    }
     private static int quotient(int numerator, int denominator) throws DivideByZeroException {
          if(denominator == 0)
               throw new DivideByZeroException();
          return(numerator / denominator);
     }

     public static void main(String args[]) {
          int number1=2, number2=0, result=0;
          try {
             result = quotient(number1,number2);
             System.out.print(number2 + " goes into " + number1);
             System.out.println(" this many times: " + result);
          }
          catch (Exception e) {
             System.out.println(e.getStackTrace()[0]);
             System.out.println("An Exception occured");
          }
     }
}

Original Trace:
QUOTE

exceptions$DivideByZeroException: an overriden getMessage() method!
at exceptions.quotient(exceptions.java:13)
at exceptions.main(exceptions.java:20)
An Exception occured


Modified Trace:
QUOTE

exceptions.main(exceptions.java:20)
An Exception occured

Hopefully these 3 tutorials have given you a full understanding of Exceptions in Java, and how useful and necessary they are in all coding.
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 10/12/08 04:05AM

Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month