Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1180747
  • 博文数量: 252
  • 博客积分: 5421
  • 博客等级: 大校
  • 技术积分: 2418
  • 用 户 组: 普通用户
  • 注册时间: 2007-06-17 12:59
文章分类

全部博文(252)

文章存档

2017年(3)

2016年(18)

2015年(31)

2014年(18)

2013年(7)

2012年(8)

2011年(12)

2010年(30)

2009年(32)

2008年(57)

2007年(36)

分类: Java

2008-03-21 15:36:03

java类成员函数中的异常处理:
1、如果函数体中含有throw语句且抛出的异常不是RuntimeException类型,则或者函数签名中包含throws部分或者将throw代码用try语句捕获。
2、如果成员函数的签名中包含throws部分,则调用该成员函数时必须进行捕获异常的处理,而不管该成员函数的函数体是否含有throw语句(虽然签名中包含throws部分但函数体中可以不包含throw语句)。
3、如果函数体中含有throw语句且抛出的异常是RuntimeException类型,则在代码中可以忽略此类异常,编译器不要求为这些类型指定异常规范,它代表一个编程错误。
 
捕获异常的办法有两种:
一、用try catch语句,而不管catch中是否进行了操作,都可以编译运行通过。
 

public class user
{
    public static void main(String args[])

    {
        user q = new user();
        q.outsay();
    }
    
    public void outsay()
    {
        try{
            say();
        }catch(Exception e){
            System.out.println("catch_error:");
            System.out.println(e.getMessage());
        }
    }
    
    public void say() throws Exception
    {
        System.out.println("call_say");
        throw new Exception("say_error");
    }
}

编译后运行输出:

call_say
catch_error:
say_error

在main函数体中捕获也一样。

二、在调用函数的签名中也声明throws,表明该函数体中可能有异常抛出,调用时需要捕获。这样调用这个外围函数时就需要捕获了,等于把异常向外传递了(真正的向外传递还需要函数体中包含throw语句,以抛出相应异常)。

public class user
{
    public static void main(String args[])

    {
        user q = new user();
        try{
            q.outsay();
        }catch(Exception e){
            System.out.println("catch_error:");
            System.out.println(e.getMessage());
        }
    }
    
    public void outsay() throws Exception
    {
        say();
    }
    
    public void say() throws Exception
    {
        System.out.println("call_say");
        throw new Exception("say_error");
    }
}

编译后运行输出:

call_say
catch_error:
say_error

也可以在main函数调用,让main函数抛出异常。

public class user
{
    public static void main(String args[]) throws Exception
    {
        user q = new user();
        q.say();
    }
    
    public void say() throws Exception
    {
        System.out.println("call_say");
        throw new Exception("say_error");
    }
}

编译后运行输出:

call_say
Exception in thread "main" java.lang.Exception: say_error
        at user.say(user.java:12)
        at user.main(user.java:6)

 

阅读(1333) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~