现在的位置: 首页 > 综合 > 正文

java的异常处理

2014年02月10日 ⁄ 综合 ⁄ 共 1811字 ⁄ 字号 评论关闭
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)

抱歉!评论已关闭.