1、异常处理代码块
try {
//可能出现异常的代码块
}catch(异常类型1 变量名1){
//异常处理方式
.....
}
.....
finally{
//一定会执行的代码块
}
//try-catch-finally 的做法是将程序的业务能力功能放在try语句中,
//将异常代码放在catch语句中,捕获并处理异常,try-catch协同工作.
2、抛出异常
(1)throws语句,用在声明方法时,表示该方法可能要抛出异常,调用者必须作出处理,捕获或者继续抛出异常。
(2)使用throws语句抛出 NumberFormatException异常
public class ThrowsExceptionTest {
public static void main(String args[])throws NumberFormatException{
//抛出NumberFormatException异常方式
Scanner in = new Scanner(System.in);
System.out.println("请输入字符串:");
String str = in.next();
int num = Integer.parseInt(str);
System.out.println(num);
}
}
3、自定义异常
public class UseRegisteTest {
public void regist(int num)throw RegisterException{//自行抛出自定义异常
if(num<0)
throw new RegisterException("注册不合理");//抛出异常对象
else
System.out.println("注册编号:"+num);
}
public static void main(String args[]){
UseRegisteTest t = new UseRegisteTest();
Scanner in = new Scanner(System.in);
System.out.println("请输入注册的编号:");
int ID = scn.nextInt();
try {
t.regist(ID);
}catch (RegisterException e){//捕获异常
e.printStackTrace();//打印自定义异常信息
}
}
}
Regis()方法用throw抛出了自定义的异常,但方法本身不处理异常,而是继续向上一层抛出,
main()方法调用regist()方法,编译器强制要求main()方法处理异常,并打印异常跟踪栈信息。