Java 在调用类本身处理异常

Java 在调用类本身处理异常,java,error-handling,Java,Error Handling,我有一个函数,它调用不同类中的另一个函数,该类根据提供的参数抛出异常。我想要 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 } } 我是

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

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
    }
}

我是否可以在
类A
本身中捕获异常并处理它?我无法更改
类B的实现

是的,只需使用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
    }
}

g()
方法调用周围使用
try catch
。当然可以。是什么让你怀疑你不能?真正的问题比你提出的更复杂吗?