处理异常的构造函数

时间:2013-01-24 11:52:55

标签: java android

如何构建可以处理IOException的构造函数

这是带构造函数的类

public class RootProcess {
Process process;

public RootProcess() throws IOException {

}

public RootProcess(Process process){
    this.process = process;
}

public Process getProcess() {
    return process;
}

public void setProcess(Process process) {
    this.process = process;
}


}

这就是我宣布它的方式

RootProcess process = new RootProcess(Runtime.getRuntime().exec("su"));

但是我在eclipse中得到了这个错误

Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor

1 个答案:

答案 0 :(得分:2)

如果从方法运行它,要么在方法签名中声明异常,要么使用try / catch块处理它。

声明例外:

public void someMethod() throws IOException {
     RootProcess process = new RootProcess(Runtime.getRuntime().exec("su"));
}

处理例外:

public void someMethod() {
try {
RootProcess process = new RootProcess(Runtime.getRuntime().exec("su"));
}
catch(IOException ex){
//handle it here
}
}