如何制作可以处理 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
最佳答案
如果您从方法运行此异常,请在方法签名中声明异常或使用 try/catch block 处理它。
声明异常:
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
}
}
关于java - 处理异常的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14500757/