Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

  • Re: General CS concepts

    Exceptions

    Exceptions are special things that interrupt normal program flow. They're used to create robust methods that follow their contracts exactly. Here's a small example:

    // * note: this code won't compile as-is, but will demonstrate our purposes here
    public int doOperation(int a, int b, char operator)
    {
         if (operator == '+')
         {
              return a+b;
         }
         else if (operator == '-')
         {
              return a-b;
         }
         else if (operator == '*')
         {
              return a*b;
         }
         else if (operator == '/')
         {
              return a/b;
         }
    }

    What happens if the operator given isn't +,-,*, or / ? What if they input doOperation(1,3,'@') (perfectly legal to the compiler)? Should you return 0? -1? Both of these values are valid return arguments, so there is no way for the calling method to distinguish between a valid output and one that's used to denote an error.

    The answer is to use exceptions. Exceptions are thrown, and then must be caught. There are two types of exceptions: unchecked, or checked. The difference is who has to catch the exception. Unchecked exceptions don't have to be caught, and checked ones do. Note: the JVM will end up catching all exceptions that get passed to it, but this is quite nasty and means your program is completely terminated.

    To throw an exception:

    throw new Exception();

    Generally, it's best not to just throw an exception, but actually inherit from the Exception class.
    Note: the Exception class is a checked exception, so it must be caught. If you want an unchecked exception, inherit from the RuntimeException class.

    So how do you catch an exception? The answer is with try/catch blocks.

    try
    {
        // code
    }
    catch(Exception e)
    {
         // stuff to do if an Exception is caught
    }

    This format will catch all exceptions (even RuntimeExceptions, which inherit from Exception). If you only want to catch a certain branch of exceptions:

    try
    {
         // code
    }
    catch(NullPointerException e)
    {
        // stuff to do if a NullPointerException is caught
    }

    Here, the catch block will catch NullPointerException's, and all children classes of NullPointerException.

    So what if you don't want your method to catch the exception, but throw it up to the caller? For unchecked exceptions, you don't have to do anything, but for checked exceptions you have to declare in the method header that your method will throw certain types of exceptions

    // note: InvalidOperatorException isn't a default Java Exception, but here pretend it extends the Exception class.
    //There is class called UnsupportedOperationException, but to demonstrate our purposes, I chose not to use it here
    public int doOperation(int a, int b, char operator) throws InvalidOperatorException
    {
        ...
    }

    Here, the doOperation declaration has a checked exception, but there's also another unchecked exception that could be thrown: the ArithmeticException, which could be thrown if the user tries to divide by 0. Note that it doesn't have to be declared that the doOperation method throws this exception, but declaring that it does doesn't force the caller to catch it.

    // will do the exact same thing as the above code
    public int doOperation(int a, int b, char operator) throws InvalidOperatorException, ArithmeticException
    {
       ...
    }

    The last section here (yes, finally got around to finishing it!) is about information you should include in your inherited exception class. For the most part, the Exception class will handle almost all of your needs. However, you may reach a time you will want to pass extra information back for debugging purposes such as the values of certain variables. Note that I haven't really had to do this, but it may become necessary when you start to work on larger Java projects. Doing this is exactly the same as it is for any other class, because Exception is a regular class that just happens to have the property of Throwable, as well as some other nice properties like getting the stack trace, but for all intensive purposes, there's nothing special about it beyond this.
    This article was originally published in forum thread: General CS concepts started by helloworld922 View original post