Declaring Checked Exceptions


A method signature can end with a throws clause followed by one or more exception types that the method can throw. A 'checked exception' is an exception that is derived from the class (or is in fact an instance of) Exception. A checked exception is not mandatory but should be declared in a method signature in the following cases::

- The 'throw' keyword is used to throw the exception in the method.
- Another method that throws the specific exception is called within the current method and the try / catch statements are not used.

If a method throws more than one exception the exception names are separated by commas.

An unchecked exception is derived from the class 'Error'. Both the Exception and Error classes are derived from the super class 'Throwable'.

Here are a couple of examples of how to use the throws clause in a method:


    public void createFile() throws IOException {
        
        //The creation of the FileWriter object may throw an
        //IOException, so it must either by caught through try / catch
        //statements or add a throws clause to the method signature,
        //else the compiler will complain.
        BufferedWriter writer = new BufferedWriter(new FileWriter("javadb.com.txt"));
        
    }

    public void convertStringToInt() throws NumberFormatException {
        
        //In this case the compiler will not complain if we don't add a throws
        //clause to the method signature or use the try / catch statements.
        //However if the conversion fails (for example if the variable s has
        //the value "123f") a NumberFormatException will be thrown and we can
        //use the throws clause to throw the exception to the caller.
        String s = "123";
        int number = Integer.parseInt(s);
        
    }

Previous     Next

Tutorial Home


Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: