异常机制
在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;
}
}