在方法之外抛出异常 - Java
Throwing exceptions outside of a method - Java
我是 Java 的初学者。
我将方法声明为 public void method() throws Exception
,但每当我尝试使用 method();
在同一 class 的另一个区域调用该方法时,我会收到错误消息:
Error: unreported exception java.lang.Exception; must be caught or declared to be thrown
如何在不出现此错误的情况下使用该方法?
在另一个调用 method()
的方法中,您将不得不以某种方式处理 method()
抛出的异常。在某些时候,它要么需要被捕获,要么一直声明到启动整个程序的 main()
方法。所以,要么捕获异常:
try {
method();
} catch (Exception e) {
// Do what you want to do whenever method() fails
}
或在您的其他方法中声明它:
public void otherMethod() throws Exception {
method();
}
您需要用类似这样的 try-catch 块包围 method()
调用:
try {
method();
} catch (Exception e) {
//do whatever
}
或者您可以在调用 method()
的方法中添加一个 throws
。
示例:
public void callingMethod() throws Exception {
method();
}
throws 关键字用于声明异常。
throw 关键字用于显式抛出异常。
如果你想定义一个用户定义异常那么....
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块用于封装可能抛出异常的代码。必须在方法内使用。
我是 Java 的初学者。
我将方法声明为 public void method() throws Exception
,但每当我尝试使用 method();
在同一 class 的另一个区域调用该方法时,我会收到错误消息:
Error: unreported exception java.lang.Exception; must be caught or declared to be thrown
如何在不出现此错误的情况下使用该方法?
在另一个调用 method()
的方法中,您将不得不以某种方式处理 method()
抛出的异常。在某些时候,它要么需要被捕获,要么一直声明到启动整个程序的 main()
方法。所以,要么捕获异常:
try {
method();
} catch (Exception e) {
// Do what you want to do whenever method() fails
}
或在您的其他方法中声明它:
public void otherMethod() throws Exception {
method();
}
您需要用类似这样的 try-catch 块包围 method()
调用:
try {
method();
} catch (Exception e) {
//do whatever
}
或者您可以在调用 method()
的方法中添加一个 throws
。
示例:
public void callingMethod() throws Exception {
method();
}
throws 关键字用于声明异常。 throw 关键字用于显式抛出异常。 如果你想定义一个用户定义异常那么....
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块用于封装可能抛出异常的代码。必须在方法内使用。