Java 实例 - 使用 catch 处理异常


以下实例演示了使用 catch 来处理异常的方法:

  1. /*
  2. author by shouce.ren
  3. Main.java
  4. */
  5.  
  6. public class Main{
  7. public static void main (String args[]) {
  8. int array[]={20,20,40};
  9. int num1=15,num2=10;
  10. int result=10;
  11. try{
  12. result = num1/num2;
  13. System.out.println("结果为 " +result);
  14. for(int i =5;i >=0; i--) {
  15. System.out.println ("数组的元素值为 " +array[i]);
  16. }
  17. }
  18. catch (Exception e) {
  19. System.out.println("触发异常 : "+e);
  20. }
  21. }
  22. }

以上代码运行输出结果为:

  1. 结果为 1
  2. 触发异常 : java.lang.ArrayIndexOutOfBoundsException: 5