11

How can I catch an exception declared in a throws clause if I don't write a try/catchclause?

  • When i write a function like this

      public List<String> getTrackIds(int limit) throws NotConnectedException, UnauthorizedException {
              ...
         } 
    

it means that the function can throw these exceptions. But isnt there a need to catch it in try/catch block? How will i catch exceptions in this case?

  • . When i try to call this function, then its mandatory to write try/catch block or write a throws clause in the calling function. Again, how will i catch these exceptions if i dont write a try/catch block?
2
  • As I mentioned in my answer below, you should also check this link to understand Catch or Specify requirement: docs.oracle.com/javase/tutorial/essential/exceptions/…
    – Pat
    Commented Jul 26, 2014 at 11:34
  • Thanks @Pat. Of course i read it. And then i posted my question after i still had some doubts.
    – Diffy
    Commented Jul 26, 2014 at 11:35

6 Answers 6

10

With Exceptions, you can either:

  • Use try catch block to handle them. (It's my problem)
  • Declare them using throws in your method specification. (It's not my problem, you deal with it)

For the latter possibility, the caller of the method has the same two options again. As you can see, the Exceptions can be declared as throws all the way up your program flow. Even static void main(String[] args) can be declared with these throws clauses, which will eventually mean your application will crash when one of the declared Exception is thrown.


Let's see the following example:

/**
 * Throws a MyException.
 */
public static void methodThrowsException() throws MyException {
    throw new MyException();
}

/**
 * Calls methodThrowsException(), and handles the thrown MyException
 */
public static void myMethod() {
    try {
        methodThrowsException();
    } catch(MyException e) {
        /* Do something */
    }
}

/**
 * Calls methodThrowsException, but does not handle the thrown MyException.
 */
public static void mySecondMethod() throws MyException {
    methodThrowsException();
}

When calling the myMethod or mySecondMethod, the following happens:

public static void main(String[] args) {
    myMethod(); /* No catching needed */
    try {
        mySecondMethod();
    } catch(MyException e){
        /* Catching needed */
    }
}

As you can see, mySecondMethod has just transferred the problem of catching the MyException to its caller.

5
  • But how will i catch the exceptions if i just use throws clause with the function?
    – Diffy
    Commented Jul 26, 2014 at 11:12
  • You don't, you let someone else catch them (i.e. the caller of the method). That someone else could be you again though, you've just moved the problem of catching the Exception to another place.
    – nhaarman
    Commented Jul 26, 2014 at 11:14
  • 1
    Okay. So throws means i want the caller of the function o deal with it. Either you catch it or transfer it to someone else.
    – Diffy
    Commented Jul 26, 2014 at 11:19
  • Indeed. I have edited the answer to include a simple example.
    – nhaarman
    Commented Jul 26, 2014 at 11:20
  • 1
    I couldn't give more +1. Pretty clear explanation :) Commented Jul 26, 2014 at 11:21
2

Suppose you have methodA, which gets called by methodB, which gets called by methodC, and so on...


Example 1:

methodA throws IOException.

Then methodB has to either throw it as well, or catch it which puts an end to the throwing. (Let's say it throws it).

So methodC has to either throw it or catch it (again, let's say it throws it).

Lets say methodD is actually the main method. Again, you have to throw it or catch it. If you throw it here, we are at the start point, there is nowhere to throw it to, so this will stop the program exeuting. Or you can catch it.


Example 2:

methodA throws IOException.

methodB again has to catch it or throw it. This time, it catches it.

methodC no longer has to throw or catch it, because it is dealt with in methodB.

3
  • This is a good example. We can end this sequence by just catching the exeption in the chain.
    – Diffy
    Commented Jul 26, 2014 at 11:23
  • Correct. And it's considered good practice to catch it as early in the chain as possible.
    – Chris
    Commented Jul 26, 2014 at 11:26
  • Ok. I will just do it. Because till now i thought just write another throws clause instead of thinking how to catch it .
    – Diffy
    Commented Jul 26, 2014 at 11:31
2

You should probably check this link to understand when should you handle the exceptions (try-catch) and when you should declare them (with throws clause): http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html

Now, to answer your questions --

But isnt there a need to catch it in try/catch block?

Not always. It depends on the type of Exception. Java has two types of Exceptions: Checked and Unchecked. And Error is a runtime situation from which recovery is not possible Read more about it at here http://docs.oracle.com/javase/tutorial/essential/exceptions/

For code that may throw checked exceptions, you MUST provide one of below:

  1. try-catch block
  2. throws clause in method declaration

For code that may throw unchecked exceptions, you are not forced by the compiler to handle them or declare them. Though, you can do one of it, if you want.

How will i catch exceptions in this case?

In your case, both NotConnectedException and UnauthorizedException are unchecked exceptions. So you can (but not forced by the compiler) write try-catch block in your method code or you can declare them in throws clause. When you declare them in throws clause the callers of the method knows that these exceptions MAY be thrown from it and plan to write their own try-catch for exception handling on their end.

When i try to call this function, then its mandatory to write try/catch block or write a throws clause in the calling function.

As I mentioned, both exceptions are unchecked (inherited from RuntimeException), so you are not required to do either. But you can do one of them.

Again, how will i catch these exceptions if i dont write a try/catch block?

you don't. The caller of the method will have to plan for exception handling with their own try-catch.

0

The try ... catch (and even finally :) ) blocks should be at the caller method.
The caller method for example is :

public void handleTracks() {

 int limit = 100;
 try {
    List<String> trackIds = getTrackIds(trackIds);
 } catch (NotConnectedException ex) {
   System.err.println("No connection was established to the tacks system. Please perform login").
 } catch (UnauthorizedException ex) {
    System.err.println("The user is unauthorized to handle the track").
 }
}

As you can see there are different treatments to the various exception types
If needed, and you're using JDK 7 and above you can have the catch block look like:

} catch (UnauthorizedException | NotConnectedException ex) {
    System.err.println("An error").
 }

This is useful in a case your method throws several exceptions, and for 2 or more exceptions you would like to have the same treatment, and for the others have a different treatment.

Another option is of course to have just a

 catch (Exception ex) {
    System.err.println("An error").
 }

But this will catch all exceptions, including the declared and non declared (Runtime exceptions which still may be thrown by the method, even if not declared at the throws part of the signature).

Hope this helps.

0

there are 3 kinds of exception

  1. Syntax error: compilation error
  2. Logical Error:-runtime
  3. Runtime error: runtime (most dangerous error)

here 1 and 2 can be solved manually by the programmer.

whereas when there is a runtime error for example:- user inputs 1/0 which is an exception and 1000 lines of code goes down the drain at that very moment.

so java developers thought how will they remove this type of problem. So they introduced 2 things :-

  1. throws
  2. try-catch finally.

so there are 2 types of exceptions in java

  1. Checked (you will always need an handler for the checked exception)
  2. Unchecked

now lets talk about how throws work:-

Throws never catches the exception. it just tells the jvm that it contains exception and the jvm should ignore this exception. now i know you will think if there is some exception in the code how will jvm handle it. jvm will throw an exception in the run time. You can only use throws with the checked execption.

whereas in try catch, Try block will see if there is any exception that that can be caught which is then caught and the further code can run.The caller of the method will have to plan for exception handling with their own try-catch.

1
  • It actually means passing it to the caller of the function. Please see the accepted answer.
    – Diffy
    Commented Jul 26, 2014 at 11:33
0

Thought I'd add another example of where I've used a custom exception and it might help to further understand how exceptions are used and how everything fits together. In a Calculator program, I have a ValidationException:

public class ValidationException extends Exception {

    public ValidationException(String msg){
        super(msg);
    }

}

I have a Controller which takes a mathematical sum as a string. I.e. it will be something like "(2 + 2) - 1 * 3".

Before calculating the answer, it goes into a Validator to check the sum if valid (it does things like check there are no letters in the sum, check its not null, check there isnt two math operators next to each other, etc.).

public class Validator {

    public void check(String sum) throws ValidationException{
        checkForNull(sum);
        checkForLetters(sum);
    }

    private void checkForNull(String sum) throws ValidationException{
        if(sum==null || sum.equals("")){
            throw new ValidationException("You must enter a sum");
        }
    }


    private void checkForLetters(String sum) throws ValidationException {
        if(.......){
            throw new ValidationException("The sum cannot contain letters");
        }
    }

}

And then the controller's handle looks like this:

public void handle(){

    String sum = view.getSumFromUser();
    try{
        validator.check(sum);
        String answer = calculator.calculate(sum);
        view.outputResponse("The answer is " + answer);
    } catch (ValidationException ex){
        view.outputResponse(ex.getMessage());
    }

}

In that last method, calculator.calculate(sum) only gets ran if validator.check(sum) completes with no exceptions.

If there is an exception, the user gets the exception message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.