异常处理

java中的异常处理分为两步

1.抛出异常

2.捕获异常

首先,我们要在类中声明可能存在异常的地方,再在调用main函数时,捕获可能抛出的异常。

抛出异常:throw new Exception ("e");  e=异常名称;

捕获异常:try{},catch{}  

实现代码:


public class Converter
{
	public int String2int(String s) throws Exception
	{
		if (s.length()>11)
			throw new Exception ("超出范围"); 
		
		int result =0;
		for (int i =0; i<s.length(); i++)
		{
			char ch = s.charAt(i);
			if (! isValid(ch))
				throw new Exception("非法字符");
			result = 10* result +(ch - '0');
		}
		
		return result;
		
	}
	private boolean isValid(char ch)
	{
		if (ch >= '0' && ch <='9') return true;
		if(ch =='-') return true;
		return false;
	}
	

public class Example
{

	public static void main(String[] args) 
	{
		Converter conv = new Converter();
		try
		{
			int result = conv.String2int("123");
			System.out.println(result);
			
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
		
		System.out.println("exit");
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值