异常处理方式:
我们可以通过两种方式处理“问题陈述”(问题陈述是任何可以引发异常的陈述)。
- 将语句括在
try-catch 块中。
- 在方法标头中附加
throws 子句。
在重写方法中处理异常:
如果您要覆盖子类中的方法。然后您不能在其签名中附加额外的 throws 子句。在您的情况下,onCreate 是父类中的一个方法,它在子类中被覆盖,因此我们不能在它的标题中附加 throws 子句。因此,您必须在 try-catch 块中的 onCreate 方法中包含任何“问题陈述”。
示例:
将语句括在try-catch 块中。
public void myMethod(){
try{
// Problem Statement
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}
}
在方法头中附加一个throws 子句。
public void myMethod()
throws IllegalAccessException, NullPointerException{
// Problem Statement
}
示例覆盖方法:
有效的 throws 子句:如果覆盖方法中的 throws 子句也在父方法中,则它是有效的。
public class Parent {
public int method()
throws IllegalAccessException,NullPointerException, Exception {
return 0;
}
}
public class child extends Parent {
// throws is part of method because parent method
// have throws clause
@Override
public int method()
throws IllegalAccessException, NullPointerException,
Exception {
//Problem Statement
return super.method();
}
}
无效的 throws 子句:如果父方法中不存在 throws 子句,则被覆盖的方法中的子句无效。
public class Parent {
public int method(){
return 0;
}
}
public class child extends Parent {
//**Error:** We can not append throws clause in the method because
// parent method do not have a throws clause
@Override
public int method()
throws IllegalAccessException, NullPointerException,
Exception {
//Problem Statement
return super.method();
}
}
因此我们必须修改子类的方法并删除 throws 子句,因为在这种特殊情况下父方法不包含 throws 子句。我们必须通过try-catch 块来处理异常。
public class child extends Parent {
//**Error:** We can not append throws clause in the method because
// parent method do not have a throws clause
@Override
public int method() {
try{
// Problem Statement
}catch(IllegalAccessException e){
e.printStackTrace();
}catch(NullPointerException e){
e.printStackTrace();
}
}
}