我怎样才能使构造函数可以处理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"));
但是我在日食中遇到这个错误
Default constructor cannot handle exception type IOException thrown by implicit super constructor. Must define an explicit constructor
最佳答案
如果从方法运行此方法,请在方法签名中声明异常,或使用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
}
}