Java异常的例子
Java异常的例子 佟强 http://blog.csdn.net/microtong 2008.11.29
对于检查型异常,Java强迫程序必须进行处理,处理的方式有以下两种:
1.声明抛出异常:不在当前方法内处理异常,而是把异常抛出到调用方法中;
2.捕获异常:使用try、catch和finally构成的语句块,捕获所发生的异常,进行相应的处理。
3.除了使用系统预定义的异常类外,用户还可以声明自己的异常类。
下面代码的输出是:
before call f2()
before call f3()
before call f4()
before call f5()
before
cn.edu.uibe.oop3.MyException: chu cuo la
at cn.edu.uibe.oop3.ExpDemo2.f5(ExpDemo2.java:36)
at cn.edu.uibe.oop3.ExpDemo2.f4(ExpDemo2.java:30)
at cn.edu.uibe.oop3.ExpDemo2.f3(ExpDemo2.java:25)
at cn.edu.uibe.oop3.ExpDemo2.f2(ExpDemo2.java:14)
at cn.edu.uibe.oop3.ExpDemo2.f1(ExpDemo2.java:8)
at cn.edu.uibe.oop3.ExpDemo2.main(ExpDemo2.java:46)
chu cuo la
Any Time
after call f3()
after call f2()
- package cn.edu.uibe.oop3;
- class MyException extends Exception{
- MyException(){
- super("myexception");
- }
- MyException(String msg){
- super(msg);
- }
- }
- public class ExpDemo2 {
- public void f1(int n){
- System.out.println("before call f2()");
- f2(n);
- System.out.println("after call f2()");
- }
- public void f2(int n){
- System.out.println("before call f3()");
- try{
- f3(n);
- }catch(MyException e){
- e.printStackTrace();
- System.out.println(e.getMessage());
- }finally{
- System.out.println("Any Time");
- }
- System.out.println("after call f3()");
- }
- public void f3(int n)throws MyException{
- System.out.println("before call f4()");
- f4(n);
- System.out.println("after call f4()");
- }
- public void f4(int n) throws MyException{
- System.out.println("before call f5()");
- f5(n);
- System.out.println("after call f5()");
- }
- public void f5(int n) throws MyException{
- System.out.println("before");
- if(n<0){
- throw new MyException("chu cuo la");
- }else{
- System.out.println("success!");
- }
- System.out.println("after");
- }
- public static void main(String[] args) {
- ExpDemo2 ed = new ExpDemo2();
- ed.f1(-100);
- }
- }