异常的基本写法:
在方法的名称中需要标注 throw Exception,并在方法体中抛出异常 throw new Exception("异常原因");
package Test;
public class Converter
{
//把字符串转换成整数
public int str2int (String s) throws Exception
//throw Exception(有些java自定义的非检查异常可以不用写throw Exception,直接在方法体中抛出即可)
{
int a = Integer.valueOf(s);
if(s.length()>11)
{
throw new Exception("超出范围"); //抛出异常,把异常原因作为参数传入Exception类
}
return a;
}
}
调用:
package Test;
public class Hello
{
public static void main(String[] args)
{
Converter c = new Converter();
try {
int b = c.str2int("123"); //用try, catch 来捕捉异常
System.out.println(b);
}
catch(Exception e)
{
e.printstacktrace(); //输出异常的详细信息,包括出错的位置等;
System.out.println(e.getMessage());
}
finally //最终一定要执行的部分
{
System.out.println("exit");
}
}
}