简体   繁体   中英

Throwing exceptions outside of a method - Java

I am a beginner in Java.

I declared a method as public void method() throws Exception , but whenever I try to call that method in another area of the same class by using method(); , I get an error:

Error: unreported exception java.lang.Exception; must be caught or declared to be thrown

How can I use that method without getting this error?

In the other method that calls method() , you will have to somehow handle the exception that method() is throwing. At some point, it either needs to be caught, or declared all the way up to the main() method that started the whole program. So, either catch the exception:

try {
    method();
} catch (Exception e) {
    // Do what you want to do whenever method() fails
}

or declare it in your other method:

public void otherMethod() throws Exception {
    method();
}

throws keyword is used to declare a Exception. and throw keyword is used to explicitly throw an exception. if u want to define a user define exception then ....

class exps extends Exception{
exps(String s){
    super(s);
 }
}

class input{
 input(String s) throws exps {
     throw new exps(s);
 }

}

public class exp{
 public static void main(String[] args){
     try{
         new input("Wrong input");
     }catch(exps e){
        System.out.println(e.getMessage());
     }
  }
}

Java try block is used to enclose the code that might throw an exception. It must be used within the method.

You need to surround the method() call with a try-catch block somewhat like this:

try {
    method();
} catch (Exception e) {
    //do whatever
}

Or you can add a throws to the method in which method() is called.
example:

public void callingMethod() throws Exception {
    method();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM