Java捕获异常

普通捕获

// 文件名 : ExcepTest.java
import java.io.*;
public class ExcepTest{
 
   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println("Access element three :" + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         //当代码试图访问数组的第三个元素的时候就会抛出一个异常。
         System.out.println("Exception thrown  :" + e);
      }
      System.out.println("Out of the block");
   }
}

多重捕获
 

try
{
  file = new FileInputStream(fileName);
  x = (byte) file.read();
}catch(IOException i)
{
  i.printStackTrace();
  return -1;
}catch(FileNotFoundException f) //Not valid!
{
  f.printStackTrace();
  return -1;
}

捕获后抛出,并执行finally中的代码善后
 

public class ExcepTest{
  public static void main(String args[]){
    int a[] = new int[2];
    try{
       System.out.println("Access element three :" + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println("Exception thrown  :" + e);
    }
    finally{
       a[0] = 6;
       System.out.println("First element value: " +a[0]);
       System.out.println("The finally statement is executed");
    }
  }
}

声明自定义异常
 

  • 所有异常都必须是 Throwable 的子类。
  • 如果希望写一个检查性异常类,则需要继承 Exception 类。
  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。
  • throws 用于方法上,可抛出多个异常,每个异常的类名用逗号隔开。

    try...catch.... 捕获异常时,大的异常(Exception类)放在下方,小的异常放在上方,否则,在异常捕获时,小的异常将不能被捕获,因为全在大的异常类中捕获到。

    即: 如果多个 catch 块中的异常出现继承关系,父类异常 catch 块放在最下面。

    处理异常的方式,不可以直接打印,或者直接输出,正确的处理方式:

  •  1.根据异常情况处理对应的逻辑
  •  2.使用文件记录异常,便于日后查看
  • // 文件名InsufficientFundsException.java
    import java.io.*;
     
    //自定义异常类,继承Exception类
    public class InsufficientFundsException extends Exception
    {
      //此处的amount用来储存当出现异常(取出钱多于余额时)所缺乏的钱
      private double amount;
      public InsufficientFundsException(double amount)
      {
        this.amount = amount;
      } 
      public double getAmount()
      {
        return amount;
      }
    }
    // 文件名称 CheckingAccount.java
    import java.io.*;
     
    //此类模拟银行账户
    public class CheckingAccount
    {
      //balance为余额,number为卡号
       private double balance;
       private int number;
       public CheckingAccount(int number)
       {
          this.number = number;
       }
      //方法:存钱
       public void deposit(double amount)
       {
          balance += amount;
       }
      //方法:取钱
       public void withdraw(double amount) throws
                                  InsufficientFundsException
       {
          if(amount <= balance)
          {
             balance -= amount;
          }
          else
          {
             double needs = amount - balance;
             throw new InsufficientFundsException(needs);
          }
       }
      //方法:返回余额
       public double getBalance()
       {
          return balance;
       }
      //方法:返回卡号
       public int getNumber()
       {
          return number;
       }
    }
    //文件名称 BankDemo.java,调用CheckingAccount类的deposit()和withdraw方法
    public class BankDemo
    {
       public static void main(String [] args)
       {
          CheckingAccount c = new CheckingAccount(101);
          System.out.println("Depositing $500...");
          c.deposit(500.00);
          try
          {
             System.out.println("\nWithdrawing $100...");
             c.withdraw(100.00);
             System.out.println("\nWithdrawing $600...");
             c.withdraw(600.00);
          }catch(InsufficientFundsException e)
          {
             System.out.println("Sorry, but you are short $"
                                      + e.getAmount());
             e.printStackTrace();
          }
        }
    }

    转载整理自:http://www.runoob.com/java/java-exceptions.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值