java的异常处理

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值