声明方法抛出异常
(1)编写程序,定义一个static方法methodA(),令其声明抛出一个IOException异常,再定义另一个static方法methodB(),在该方法中调用methodA()方法,在main()方法中调用methodB()方法。试编译该类,看编译器会报告什么?对于这种情况应如何处理?
代码如下:
import java.io.IOException;
public class ThrowExceptionDemo {
public static void methodA() throws IOException{
}
public static void methodB(){
methodA();
/***********************************
直接调用方法编译器会报错:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException
at ThrowExceptionDemo.methodB(ThrowExceptionDemo.java:9)
at ThrowExceptionDemo.main(ThrowExceptionDemo.java:28)
应该加上以下注释代码:
************************************/
// try {
// methodA();
// } catch (IOException e) {
// e.printStackTrace();
// }
}
public static void main(String[] args){
methodB();
}
}
直接编译的话会报错:
然后将注释代码添加进去就可以解决。
用throw语句抛出异常
(2)创建一个自定义的异常类,该类继承Exception类,为该类写一个构造方法,该构造方法带一个String类型的参数。写一个方法,令其打印出保存下来的String对象。再编写一个类,在main()方法中使用try-catch结构创建一个MyException类的对象并抛出,在catch块中捕获该异常并打印传递的String消息。
代码如下:
public class MyException extends Exception {
private String s;
public MyException(String message) {
this.s = message;
}
//打印保存下来的String对象
public void PrintString(){
System.out.println(s);
}
}
class TestMyException {
public static void main(String[] args) {
try{
throw new MyException("这是String消息");
} catch(MyException exc){
exc.PrintString();
}
}
}