133
class throwseg1
{
    void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

    void show2() throws Exception  // Why throws is necessary here ?
    {
        show();
    }

    void show3() throws Exception  // Why throws is necessary here ?
    {
        show2();
    }

    public static void main(String s[]) throws Exception  // Why throws is necessary here ?
    {
        throwseg1 o1 = new throwseg1();
        o1.show3();
    }
}

Why compiler reports that methods show2(), show3(), and main() have

unreported exception Exception that must be caught or declared to be thrown

when I remove throws Exception from these methods?

user2864740
  • 60,010
  • 15
  • 145
  • 220
nr5
  • 4,228
  • 8
  • 42
  • 82
  • 2
    @PaulTomblin main certainly can be declared to throw Exception. If it does, the JVM will shut down. This is as close to ignoring it as the compiler will allow. – Taymon Jul 21 '12 at 03:57
  • 1
    When the called method (**Methdod1**) throws `Exception`, we have to define the calling method (**Method2**) with `throws Exception`; if we are not handing that exception in the calling method. The purpose of this is to give heads up to the calling method (**Method3**) of **Method2** that an Exception may be thrown by **Method2** and you should handle it here, else it may interrupt your program. – Rito Sep 11 '17 at 02:03
  • Similarly, if **Method3** is not handling the exception in its body then, it had to define `throws Exception` in its method definition to give heads up its calling method. _extension of the previous comment_ – Rito Sep 11 '17 at 02:11

8 Answers8

187

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

enter image description here

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

Devin Ersoy
  • 354
  • 3
  • 12
Jomoos
  • 12,823
  • 10
  • 55
  • 92
  • 1
    what i got from your answer is that the Error class and its sublaclasses and RuntimeException class and its sub classes , they come under unchecked exception (like System.out.println(5/0); there is no need to throw as its is a runtime exception but still we can apply try catch) and Exception class is checked so we need to declare throws clause in that method and every method that calls it – nr5 Jul 21 '12 at 04:45
  • One more questions: if the exceptions are categorized into unchecked and checked, specially the unchecked ones(runtime errors) to avoid more number of errors during compile time ? – nr5 Jul 21 '12 at 05:04
  • @Jomoos - Say that the code inside a method throws IOException. Then, is it okay to put "throws Exception" in the method's declaration ? – MasterJoe Dec 05 '17 at 06:54
  • 1
    oh. I get it now. there's an exception to the rules of the Exception hierarchy. Makes. Perfect. Sense. Thanks Java. – JJS Oct 26 '18 at 14:32
34

Java requires that you handle or declare all exceptions. If you are not handling an Exception using a try/catch block then it must be declared in the method's signature.

For example:

class throwseg1 {
    void show() throws Exception {
        throw new Exception();
    }
}

Should be written as:

class throwseg1 {
    void show() {
        try {
            throw new Exception();
        } catch(Exception e) {
            // code to handle the exception
        }
    }
}

This way you can get rid of the "throws Exception" declaration in the method declaration.

jebar8
  • 2,113
  • 3
  • 21
  • 31
  • 9
    All exceptions which are not subclasses of `RuntimeException`, that is. – yshavit Jul 21 '12 at 04:25
  • if there is any other class like Exception that is checked ? – nr5 Jul 21 '12 at 05:12
  • 1
    What do you mean? Since all exception objects have "Exception" as their base class, if you catch an "Exception" object (like in my example) it will catch any exception that is thrown. To be more specific (since different exceptions will probably require different ways of handling things) you should have multiple catch blocks. – jebar8 Jul 21 '12 at 05:19
  • if I were to say that checked exceptions need to be handled @ compile time and caught at runtime . Am i right ? if yes then phrasing the same sentence for Unchecked exception would be ? – nr5 Jul 21 '12 at 05:22
  • @jebar8 -- you're confusing Java with .NET -- in Java, throwables must inherit `Throwable` (inheriting `Exception` also works, because it extends `Throwable`, but it's not required). – BrainSlugs83 Jun 15 '20 at 22:11
10

The throws Exception declaration is an automated way of keeping track of methods that might throw an exception for anticipated but unavoidable reasons. The declaration is typically specific about the type or types of exceptions that may be thrown such as throws IOException or throws IOException, MyException.

We all have or will eventually write code that stops unexpectedly and reports an exception due to something we did not anticipate before running the program, like division by zero or index out of bounds. Since the errors were not expected by the method, they could not be "caught" and handled with a try catch clause. Any unsuspecting users of the method would also not know of this possibility and their programs would also stop.

When the programmer knows certain types of errors may occur but would like to handle these exceptions outside of the method, the method can "throw" one or more types of exceptions to the calling method instead of handling them. If the programmer did not declare that the method (might) throw an exception (or if Java did not have the ability to declare it), the compiler could not know and it would be up to the future user of the method to know about, catch and handle any exceptions the method might throw. Since programs can have many layers of methods written by many different programs, it becomes difficult (impossible) to keep track of which methods might throw exceptions.

Even though Java has the ability to declare exceptions, you can still write a new method with unhandled and undeclared exceptions, and Java will compile it and you can run it and hope for the best. What Java won't let you do is compile your new method if it uses a method that has been declared as throwing exception(s), unless you either handle the declared exception(s) in your method or declare your method as throwing the same exception(s) or if there are multiple exceptions, you can handle some and throw the rest.

When a programmer declares that the method throws a specific type of exception, it is just an automated way of warning other programmers using the method that an exception is possible. The programmer can then decide to handled the exception or pass on the warning by declaring the calling method as also throwing the same exception. Since the compiler has been warned the exception is possible in this new method, it can automatically check if future callers of the new method handle the exception or declare it and enforcing one or the other to happen.

The nice thing about this type of solution is that when the compiler reports Error: Unhandled exception type java.io.IOException it gives the file and line number of the method that was declared to throw the exception. You can then choose to simply pass the buck and declare your method also "throws IOException". This can be done all the way up to main method where it would then cause the program to stop and report the exception to the user. However, it is better to catch the exception and deal with it in a nice way such as explaining to the user what has happened and how to fix it. When a method does catch and handle the exception, it no longer has to declare the exception. The buck stops there so to speak.

dansalmo
  • 11,506
  • 5
  • 58
  • 53
4

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

Taymon
  • 24,950
  • 9
  • 62
  • 84
  • Every method in the chain is declared to throw Exception, including main. So where's the problem? – Paul Tomblin Jul 21 '12 at 04:09
  • @PaulTomblin i m asking that that why is it necessary to write throws exception in the calling functions, calling a function that throws an exception – nr5 Jul 21 '12 at 04:14
  • Ok, I didn't understand why you were asking about a compiler error that you weren't actually getting from the code you posted. That's an odd way of asking. – Paul Tomblin Jul 21 '12 at 04:15
0
package javaexception;


public class JavaException {
   void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

void show2() throws Exception  // Why throws is necessary here ?
{
    show();
}

void show3() throws Exception  // Why throws is necessary here ?
{
    show2();
}
public static void main(String[] args) {

   JavaException a = new JavaException();

   try{
   a.show3();
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
}

Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

tawess
  • 1
0
void show() throws Exception
{
    throw new Exception("my.own.Exception");
}

As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.

void show2() throws Exception //Why throws is necessary here ?
{
show();
}

Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.

Aditya
  • 43
  • 9
0

Basically, if you are not handling the exception in the same place as you are throwing it, then you can use "throws exception" at the definition of the function.

0

If you propagate the exception by declaring the throws directive in the signature of the current method, then somewhere up the line or call stack a try/catch construct must be used to handle the exception.

  • This comment should be added to the comments section as it does not provide a verifiable answer or an example of one. - https://stackoverflow.com/help/how-to-answer – Paul Dawson Jul 26 '19 at 12:33