zoukankan      html  css  js  c++  java
  • try catch 和\或 finally 的用法

    1) try catch finally中的finally不管在什么情况之下都会执行,执行的时间是在程序return 之前.

    2) Java 编译器不允许有显示的执行不到的语句块,比如return之后就不可能再有别的语句块(分支不属于此列) 所以以下程序编译

    实例捕捉一个错误

    public class MainClass {
      public static void main(String args[]) {
        int d, a;

        try

        {
          d = 0;
          a = 42 / d;
          System.out.println("This will not be printed.");
        }

       catch (ArithmeticException e)

       { 
          System.out.println("Division by zero.");
        }
        System.out.println("After catch statement.");
      }
    }

    try可以没有catch,try还可以和finally{}搭配,但是有try必须有catch或者finally中的一个。

    还有,如果不想在这个方法里处理,而在调用的方法里一起处理的话,可以直接在方法的签名也就是方法名后的小括号后面,加throws Exception,把异常抛给别人

    实例

    import java.util.Random;

    public class MainClass {
      public static void main(String args[]) {
        int a = 0, b = 0, c = 0;
        Random r = new Random();

        for (int i = 0; i < 32000; i++) {
          try {
            b = r.nextInt();
            c = r.nextInt();
            a = 12345 / (b / c);
          } catch (ArithmeticException e) {
            System.out.println("Division by zero.");
            a = 0; // set a to zero and continue
          }
          System.out.println("a: " + a);
        }
      }
    }

    不错的博客http://blog.csdn.net/lovecj6185/article/details/4461516

  • 相关阅读:
    关于firstChild,firstElementChild和children
    trim(),正则表达式中文匹配
    Shell之基本用法
    Samba服务部署
    Linux基础(3)
    linux基础(2)
    Linux基础(1)
    网络基础及网络协议
    操作系统简介
    为何要学习计算机基础
  • 原文地址:https://www.cnblogs.com/liuyuanyuanGOGO/p/try_catch_finally.html
Copyright © 2011-2022 走看看