try-catch异常抛出与捕获

    科技2024-01-03  107

    什么时候要考虑异常? 所谓异常就是程序运行时可能出现的一些错误,比如试图打开一个根本不存在的文件,或者除法运算时除数为0,再或者根据实际的业务来判断是否会出现异常。 这里是java的异常类的继承关系树:

    try-catch-finally结构

    try { //包含可能发生异常的语句 call methodA() and maybe throw an exception; call methodB() and maybe throw an exception; call methodC() and maybe throw an exception; everything is OKay, so display finalresult; }catch(methodA()'s Exception/Error e) //这里的“methodA()'s Exception/Error”指的是异常的类名,e为这个类的对象 { set error code to methodA(); } …………//表示methodB()和methodC()的异常处理方法与methodA()大致类似 finally { //执行必须要做的操作,既是否发生异常都会执行的步骤。 }

    throws-throw结构 举个例子: //在自己编写的方法中主动抛出异常 // 方法本身不对异常捕获和处理,而由调用它的方法去处理 class MyMath{ public int div (int i, int j) throws Exception { //或ArithmeticException return (i / j) ; } } //主类 public class test_vector{ public static void main(String args[]){ MyMath m = new MyMath() ; try{ int temp = m.div(10, 0) ; System.out.println(temp) ; }catch (Exception e){ System.out.println("捕获 除数为零异常") ; //e.printStackTrace(); // 打印异常 } //throw new Exception("抛着玩的。") ; // 人为抛出 } }

    通过这条语句可以将异常所在打印出来,比如

    再或者可以将代码修改成这样:

    //在自己编写的方法中主动抛出异常 // 方法本身不对异常捕获和处理,而由调用它的方法去处理 //import java.lang.Exception; class MyMath{ public int div (int i, int j) throws Exception { //或ArithmeticException return (i / j) ; } } //主类 public class test_vector{ public static void main(String args[])throws Exception{ MyMath m = new MyMath() ; try{ int temp = m.div(10, 0) ; System.out.println(temp) ; }catch (Exception e){ System.out.println("捕获 除数为零异常") ; e.printStackTrace(); // 打印异常 } throw new Exception("抛着玩的。") ; // 人为抛出 } }

    这里与前者的不同就是在主类后面加入了一个throws Exception表明通过程序员自己抛出异常。

    用户自己自定义异常 由于JDK手册中的异常种类可能会不满足程序员的需要,但是重新写完一个异常类是在复杂,所以我们可以运用JAVA的特性——完全面向对象,用“继承”的方法来自定义异常类 。 一个方法在声明时可以使用throws关键词声明要产生的若干个异常,并在该方法的方法体中给出产生异常的操作,即用相应的异常类创建对象,并使用thorw关键词抛出该异常对象,导致该方法结束执行。 程序必须在try-catch块语句中调用可能发生异常的方法,其中catch的作用就是捕获throw关键字抛出的异常对象。 一个例子: class BankException extends Exception { String message; public BankException(int m,int n) { message = "入账资金"+m+"是负数或支出"+n+"是正数,不符合系统要求"; } public String warnMess() { return message; } } class Bank { private int money; public void income(int in,int out) throws BankException { if(in <= 0 || out >= 0 ||in + out <=0) { throw new BankException(in,out); } int netIncome = in + out; System.out.printf("本次计算出的纯收入是:%d元\n",netIncome); money = money + netIncome; } public int getMoney() { return money; } } public class test_vector { public static void main(String args[]) throws BankException { Bank bank = new Bank(); try{ bank.income(200,-100); bank.income(300,-100); bank.income(400,-100); System.out.printf("银行目前有%d元\n",bank.getMoney()); bank.income(200,100); bank.income(9999,-100); }catch (BankException e) { System.out.println("计算收益出现以下问题:"); System.out.println(e.warnMess()); } System.out.printf("银行目前有%d元\n",bank.getMoney()); } }

    Processed: 0.011, SQL: 8