26

when you do this:

public class Blah {

    public void doBlah() throws BlahException {

    }

}

What does adding the throws BlahException really do?

Does it basically group any exception to that one? i.e. if there is an exception, no matter what it is, will always be thrown using BlahException?

mikej
  • 65,295
  • 17
  • 152
  • 131
mrblah
  • 99,669
  • 140
  • 310
  • 420

4 Answers4

27

It tells the clients of your class that the DoBlah method can throw a BlahException or any other exception that extends it.

If it's a checked exception, the compiler will require that they wrap calls to this method in a try/catch block. If it's unchecked, they can choose to not catch the exception, but they have to be aware that if they don't it'll be bubbled further up the call stack.

It doesn't say anything about unchecked exceptions like NullPointException or errors. Those can always be thrown as well. They aren't required in the throws clause.

This code shows how it works:

ExceptionDemo.java:

package exceptions;

public class ExceptionDemo
{
    public static void main(String[] args)
    {
        ExceptionDemo demo = new ExceptionDemo();

        try
        {
            // Removing the try/catch will result in a compilation error
            demo.doChecked();            
        }
        catch (CheckedException e)
        {
            e.printStackTrace();
        }

        // Note: Not inside a try/catch, in spite of the throws clause
        demo.doUnchecked();
    }

    public void doChecked() throws CheckedException
    {
        System.out.println("doing something that may throw a checked exception");
    }

    // Note: "throws" clause is unnecessary for an unchecked exception
    public void doUnchecked() throws UncheckedException
    {
        System.out.println("doing something that may throw an unchecked exception");
    }
}

CheckedException.java:

package exceptions;

public class CheckedException extends Exception
{
    public CheckedException()
    {
        super();
    }

    public CheckedException(String message)
    {
        super(message);
    }

    public CheckedException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public CheckedException(Throwable cause)
    {
        super(cause);
    }
}

UncheckedException.java:

package exceptions;

public class UncheckedException extends RuntimeException
{
    public UncheckedException()
    {
        super();
    }

    public UncheckedException(String message)
    {
        super(message);
    }

    public UncheckedException(String message, Throwable cause)
    {
        super(message, cause);
    }

    public UncheckedException(Throwable cause)
    {
        super(cause);
    }
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 1
    Bizarrely, there's no mention at all that I can find of Exceptions in the Java Tutorial (http://java.sun.com/docs/books/tutorial/java/TOC.html). What a peculiar omission. – skaffman Jan 01 '10 at 17:28
  • Just for my curiosity, how exactly do you specify whether a (user-defined) exception is supposed to be checked or unchecked? Is it as simple as having it appear in that "throws" section, or is there something you have to do in the exception class itself? – Platinum Azure Jan 01 '10 at 17:30
  • 2
    @skaffman Exceptions are covered in Essential Java Classes (http://java.sun.com/docs/books/tutorial/essential/index.html) rather than Learning the Java Language. – mikej Jan 01 '10 at 17:32
  • @Platinum Azure unchecked exceptions are those that extend from either java.lang.RuntimeException or java.lang.Error i.e. when defining a user-defined exception it comes down to what you specify as the superclass. – mikej Jan 01 '10 at 17:34
  • Ah, so if it extends from java.lang.Exception and I specify it in a throws clause, it must necessarily be a checked exception? – Platinum Azure Jan 01 '10 at 17:35
  • @mikej: Ah, so they are. Odd place to put them, exceptions are a language feature, and an important one. – skaffman Jan 01 '10 at 17:35
  • @skaffman, I agree. I'm not sure if you can get through all the material in the first tutorial without having to known anything about exceptions. – mikej Jan 01 '10 at 17:39
  • @Platinum Azure: Unless they extend RuntimeException, which extends Exception. In other words, checked exceptions are: Exception and all suclasses of Exception except RuntimeException and its subclasses. – Carl Smotricz Jan 01 '10 at 17:40
  • @Platinum Azure if you create a user-defined exception that extends from java.lang.Exception then it is a checked exception. Hence if a method you write explicitly has a statement throw new YourCheckedException() or calls another method that has throws YourCheckedException in its throws clause then the original method must either be declared throws YourCheckedException (or a superclass) as well or must enclose the call to the other method in a try/catch. – mikej Jan 01 '10 at 17:41
14

No. the throws BlahException clause tells the compiler that your function might throw a BlahException and that this should be caught by the caller. For example:

class ExceptionThrower
{
    void someFunction()
    {
        for(int i =0; i<10;i++)
            if(i==4) throw new Exception();
    }

    public static void main(String args[])
    {
        new ExceptionThrower().someFunction();
    }
}

This program will not compile, because it can throw an exception of type Exception, and the exception has neither been caught nor declared to be thrown.

However, the following code will compile fine.

class ExceptionThrower
{
    void someFunction() throws Exception
    {
        for(int i =0; i<10;i++)
            if(i==4) throw new Exception();
    }

    public static void main(String args[])
    {
        try
        {
            new ExceptionThrower().someFunction();
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

Essentially, you are telling the compiler that this function might throw an Exception that is not handled inside the function itself. These types of exceptions are all subclasses of java.lang.Exception and are called checked exceptions. Other exceptions that indicate a catastrophic failure caused by bugs in the program itself, rather than by a condition such as malformed input are subclasses of java.lang.RuntimeException and these are called unchecked exceptions. In short, unchecked exceptions can be thrown without a throws clause in the method signature, while any checked exceptions must be indicated there.

For a discussion of checked vs. unchecked exceptions see http://www.javapractices.com/topic/TopicAction.do?Id=129

Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114
  • 3
    that is not true for unchecked exceptions. They can be declared in the method signature for documentation reasons, but don't need to be caught by clients. – manuel aldana Jan 01 '10 at 18:39
4

The whole idea is that without throws keyword, the exception raised by the method cannot be handled outside the method.

Isn't it so?

John Weisz
  • 30,137
  • 13
  • 89
  • 132
TheJoker
  • 100
  • 8
1

Your method doBlah() need to have something that can throw BlahException or any subclass of BlahException. This tells caller of doBlah() to be careful usually to wrap the code in try-catch.

fastcodejava
  • 39,895
  • 28
  • 133
  • 186