在Java中,经常会出错,存在异常现象,遇到问题该怎么处理呢,下面来让我们认识几个大将:
try : Java 中擅长监控敌人的大将
catch : 擅长捕获和处理敌人的大将
finally :擅长收拾战场的大将
throw : 用来抛出异常,而自己不处理throws :用来声明方法有可能抛出各种异常
让我们来看看这几位大将怎么用吧!
public class Xx {
public static void main (String[] args){
Public double money (int age) throws Exception {
if (age>16){
throw new Exception ("年龄不能小于16")
}else{
int jialing =age -16;
if (jialing<4){
return 1000;
}else {
return 600;
}
}
}}}
在编写一个测试类
Public class TestXx {
Scanner input =new Scanner (System.in);
System .out .println ("请输入您的年龄");
int age =input .nextInt();
Xx aa =new Xx ();
try {
System .out .println ("你的保险金额是"+aa.money(age));
}catch (Exception e){
System .out .println (e.getMessage());
e.printStackTrace ();
}}
这样,我们就可以检测到可能会出现的异常,同时try语句后边可以跟多个catch块,他们就可以用来捕获多种不同的异常,catch块捕获异常的顺序是从小到大的先捕获Exception 的子类对象,最后才能捕获Exception 类的对象。