[java] Why is "throws Exception" necessary when calling a function?

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?

The answer is


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


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.


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.


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.


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.


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.


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.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to exception-handling

Catching FULL exception message Spring Resttemplate exception handling How to get exception message in Python properly Spring Boot REST service exception handling java.net.BindException: Address already in use: JVM_Bind <null>:80 Python FileNotFound The process cannot access the file because it is being used by another process (File is created but contains nothing) Java 8: Lambda-Streams, Filter by Method with Exception Laravel view not found exception How to efficiently use try...catch blocks in PHP

Examples related to unhandled-exception

What is an unhandled promise rejection? Java 8: How do I work with exception throwing methods in streams? Why is "throws Exception" necessary when calling a function?

Examples related to throws

Why is "throws Exception" necessary when calling a function? Error message "unreported exception java.io.IOException; must be caught or declared to be thrown" When to use throws in a Java method declaration?

Examples related to checked-exceptions

How can I throw CHECKED exceptions from inside Java 8 streams? How do I fix a compilation error for unhandled exception on call to Thread.sleep()? Why is "throws Exception" necessary when calling a function? Understanding checked vs unchecked exceptions in Java