Java异常机制

异常机制

在Java里,使用异常机制来进行出错处理
异常:Exception (路径:java.lang.Exception)

处理模式

1、在方法里抛出异常
2、在调用时捕获异常

抛出异常

在检测到错误发生时,抛出异常对象

int str2int (String str) throws Exception
{
	if(/*错误1发生*/)
		throw new Exception("错误1");
	if(/*错误2发生*/)
		throw new Exception("错误2");
}

规则:
1、在方法后面加throws Exception
用来声明该方法里可能会出错,可能会抛出异常

2、在出错时,用throw语句抛出异常对象

捕获异常

在调用时,使用try……catch……来捕获异常

try
{
	//… 可能抛出异常的代码 …
}
catch(Exception e)
{
	//… 异常处理 …
}

try:监视若干代码,如果里面抛出异常,则进入catch{}。
catch:出错处理,参数为刚刚抛出的异常对象,所有的出错信息都在异常对象里。

异常处理机制示例

package my;
public class Test
{
	public static void main(String[] args)
	{
		Converter conv = new Converter();
		try {
			int result = conv.str2int("201k8");
			System.out.println("正常:" + result);
		}
		catch( Exception e)
		{
			System.out.println(e.getMessage());
		}
		System.out.println("exit");
	}
}
package my;
public class Converter
{
	// 把一个字符串转成整数
	// 例如: "123" ->  123
	public int str2int (String str) throws Exception
	{
		if(str.length()>11)
		{
			Exception ex = new Exception("超出范围");
			throw ex;
		}
		int result = 0;
		for(int i=0; i<str.length(); i++)
		{
			char ch = str.charAt(i);
			if( ! isValid(ch) )
				throw new Exception("非法字符");
			result = result * 10 + (ch - '0'); 			
		}
		return result;
	}
	private boolean isValid(char ch)
	{
		if(ch >= '0' && ch <= '9')return true;
		if(ch == '-') return true;
		return false;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值