Java语言系统 异常-补充.pptVIP

  • 1
  • 0
  • 约1.16万字
  • 约 35页
  • 2019-12-02 发布于湖北
  • 举报
思考 public class Try1 { public static void main(String args[]) { int i = 0, sum = 0, n = 0; int a[] = { 5, 6, 7, 8 }; try { for (i = 0; i = 5; i++) { System.out.println(a[i]); sum += a[i]; } System.out.println(平均值 + (sum / n)); } catch (Exception e) { System.out.println(异常: + e.toString()); }catch (ArrayIndexOutOfBoundsException e) { System.out.println(数组异常: + e.toString()); } } } 示例:抛出异常 public class DivException { public double method() throws Exception{ int a,b; Scanner sc=new Scanner(System.in); System.out.println(请输入a,b的值:); a=sc.nextInt(); b=sc.nextInt(); if(b==0){ throw new Exception(); }else{ return a/b; } } public static void main(String[] args) throws Exception {//第一种处理方式:继续抛出 DivException d=new DivException(); d.method();//此方法的调用者必须对抛出的异常做处理,要么继续抛出,要么用try进行处理 } } * 例子:余额处理 class Bank { double balance; //余额 public void deposite(double amount) { // 存钱 if (amount 0.0) balance += amount; } public void withdrawal(double amount) // 取款 throws InsufficientFundsException //必须抛出,否则编译出错 { if ( balance amount ) { throw new InsufficientFundsException(this, amount); } balance = balance-amount; } public double getBalance() { //获取余额 return balance; } } * 例子:余额处理 public class ExceptionDemo { public static void main(String args[]) { try { Bank bank = new Bank(); bank.deposite(50); bank.withdrawal(100); System.out.println(“Withdrawal successful!”); } catch(InsufficientFundsException e){ System.out.println(e.toString()); } } } * 异常小结 对Error类或其子类对象,程序中不必进行处理 对RuntimeException类或其子类,程序中可以不必进行处理,这类异常表示程序员设计程序时有错误,故程序员应改正,以消除发生这类异常 除此之外的

文档评论(0)

1亿VIP精品文档

相关文档