0

我有一个函数调用不同类中的另一个函数,该函数根据提供的参数引发异常。我想

public class A {
    public int f(int p){
    {
         B obj = new B();
         obj.g(p);
    }
}

public class B {
    public int g(int p)
    {
        // throws an exception for this value of p
    }
}

我是否有可能自己捕获异常class A并处理它?我无法更改class B.

4

1 回答 1

1

是的,只需使用 try-catch 语句。

public class A {
    public int f(int p){
    {
         B obj = new B();
         try {
             obj.g(p);
         } catch ( /* the exception */ ) {
             // handle the exception
         }
    }
}

public class B {
    public int g(int p)
    {
        // throws an exception for this value of p
    }
}
于 2013-09-12T17:48:07.503 回答