3

After studying more and more about throws statement in Exception Handling I am getting confused.I found-

If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.

class Boxing1{  
public static void main(String args[]) throws IOException{
    new B().meth2();
    System.out.println("33333333");
}
}
class A{

    void meth1() throws IOException{
        throw new IOException();
        //throw new NullPointerException();
        //System.out.println("111111111111");
    }
}
class B{
    void meth2() throws IOException{
        new A().meth1();
        System.out.println("2222222");
    }
}

Instead of using throws there is still an exception- My console is showing following error-

Exception in thread "main" java.io.IOException
    at A.meth1(Boxing1.java:17)
    at B.meth2(Boxing1.java:24)
    at Boxing1.main(Boxing1.java:10)

Untill I am not putting calling of meth1 in try-catch block there is a exception in spite of using throws. What is the role of throws here?

try{new A().meth1();}catch(Exception e){System.out.println(e);}

I needed your confirmation on it.I am confused.My one line Query is-

Is there any other role of throws instead of propagating a CheckedException?

TheCurious
  • 593
  • 1
  • 4
  • 29
  • add the code in the question? – Veselin Davidov May 05 '15 at 09:18
  • 9
    You can also add `throws SomeRuntimeException`. It's redundant for the compiler, but it's useful as a documentation. – JB Nizet May 05 '15 at 09:18
  • 1
    Why do you think it may do something else? Have you read something about that? Or asked differently ... why are you confused? Have you found a contradiction in the descriptions about `throws`? – Tom May 05 '15 at 09:21
  • @Tom some documents are saying it is for to tell jdk there is a chance that here this exception can occure and i am not handling it now.you will take care about it. – TheCurious May 05 '15 at 09:26
  • 3
    Your statement above is almost correct - "it is for to tell THE CALLING CLASS there is a chance that here this exception can occure and i am not handling it now.you will take care about it." – DaveH May 05 '15 at 09:28
  • 1
    @dubey-theHarcortians And where is the confusion about that? This is the same as you wrote in your question, so I still don't know what your question is. – Tom May 05 '15 at 09:32
  • 1
    *"Instead of using throws there is still an exception"* To which method should the `main` method propagate its exception? There is nothing "above" it that will handle that exception, so it remains unhandled. – Tom May 05 '15 at 09:48
  • I studied in many documents that-The Java throws keyword is used to declare an exception.what does it mean? – TheCurious May 05 '15 at 11:57
  • 1
    @dubey-theHarcortians `throws` tells the calling method, that the called method _might_ throw either the mentioned exception or a subclass of it. If the exception is a _checked exception_, then the calling method should handle it or propagate it to its calling method (using `throws`). – Tom May 05 '15 at 12:02

3 Answers3

3

I think that exceptions handling is very logical and throws is necessary, because you do not always want to handle the exception at the level it may occur.

Let's say you have an object that manages values existing in multiple files

public class MultipleFileManager {
    private List<String> filesContent;
    .
    . 
    .
    public void addFileContent(String filename) {
        File file = new File(filename);
        try {
            FileReader fr = new FileReader(file);
            .
            //adding filecontent to filesContent list
            .
        } catch (IOException e) {
            System.err.println("file not added");
        }
    }
}

In this example, you obviously want to handle the exception at the MultipleFileManager level, because it would be very wrong if just one corrupted file could crash the whole thread.

Therefore throws IOException statement in the FileReader class methods tells you that you either will handle the exception at the level of addFileContent() level, or you risk crashing your entire thread in which the exception is thrown if you encounter corrupted file.

And if it so happens that this thread is a main thread, entire application will crash.

pnadczuk
  • 907
  • 1
  • 7
  • 12
  • 2
    *"or you risk crashing your entire app"* ... you mean "or you risk crashing your current thread". If the current thread is the "main" thread, then it will crash the application, but if not, then just that thread dies. – Tom May 05 '15 at 10:17
  • Thanks for spotting mistake and clarification, I will edit the answer – pnadczuk May 05 '15 at 10:30
2

As you said, there are 2 kinds of exceptions.

  • "Checked exceptions" need the attention of the developer. When you use a method that throws a checked exception (i.e. IOException), you need to handle it (i.e. catch it) or propagate it to the caller (i.e. throw it) assuming that the caller will catch it.

  • "Unchecked exceptions" don't need special attention. These are exceptions like NullPointerException, bugs. You don't want to write code to cover potential bugs. It's impossible to cover everything. Nevertheless, if you want to catch an unchecked exception, you can.

  • Note: There are some other throwable objects. You can throw all objects that extend the Throwable class. But you shouldn't use this functionality in your code. This is really for system Errors and Assertions.

If you throw a checked exception then you need to warn developers by specifying throws SomeException in your method signature. For an unchecked exception you don't.

The compiler checks this. It recognizes unchecked exceptions easily, because unchecked exceptions extend the RuntimeException class.

Finally, in your case you propagated the exception all the way to the top, to your main() method. And even there you continued propagating it. The JVM will just print it in that case.

bvdb
  • 22,839
  • 10
  • 110
  • 123
  • I am looking for only yes or No as answer.Only describe If there is any other role of throws exist instead of prapogating checked exception. – TheCurious May 05 '15 at 11:01
  • 1
    There is no other role. It is only to propagate exceptions. But you cannot only use it for checked exceptions, also for unchecked (but then it's not mandatory), and for Errors (which is a seperate class of `Throwable`'s). Errors are usually Operating System errors which you don't want to cover neither. – bvdb May 05 '15 at 11:03
  • I studied in many documents that-The Java throws keyword is used to declare an exception.what does it mean? – TheCurious May 05 '15 at 11:57
  • 1
    @dubey-theHarcortians It just means that you specify which exceptions a method can create. Then when you (or another developer) wants to use this method, he can see which exceptions it could cause just by looking at the method's header. (e.g. if you write a method `openFile` which is trying to open a text file. You know that the file does not always exist, so your code may cause a `FileNotFoundException`. In that case just put `throws FileNotFoundException` behind your method signature. like: `public void openFile(String filename) throws FileNotFoundException { ... }` – bvdb May 05 '15 at 12:13
2

Lets diagnose:

First of all you program will throw an exception because of the code

throw new IOException();

When you put a try catch block, the exception will be handled in the catch block.

Remember there are two types of Exceptions: Checked and Unchecked Exceptions and then there are Errors.

The throw keyword just raises an exception(it can be a custom exception too!!!) and halts the execution (if no catch is used to deal with the exception)

In general practice:

  • The catch block will handle the Exception
  • Throws will pass the error to his caller with no recovery mechanism.
bvdb
  • 22,839
  • 10
  • 110
  • 123
0o'-Varun-'o0
  • 735
  • 1
  • 5
  • 22
  • I am looking for only yes or No as answer.Only describe If there is any other role of throws exist instead of prapogating checked exception. – TheCurious May 05 '15 at 11:01
  • @bvdb explained it to you. Its about the perspective of implementation. Throwing something checked or unchecked or you can use it with your own usage. May be you should try some real life scenarios. – 0o'-Varun-'o0 May 05 '15 at 11:11
  • I studied in many documents that-The Java throws keyword is used to declare an exception.what does it mean? – TheCurious May 05 '15 at 11:57
  • 1
    I will give u an example ... u want copy paste a text file to another location ... u wrote a program to do this job .... but by human mistake u typed misspelled name of the text file ... or the file ur program is looking for is not existing ... at such situations ur program needs to deal with such situations .... exceptions are kind of alert mechanizm to pin point the cause of the problem – 0o'-Varun-'o0 May 05 '15 at 14:54