zoukankan      html  css  js  c++  java
  • 章节六、2-异常---运行时异常

    一、案例演示(除数为0运行时异常)

    1、创建一个名为RuntimeExceptionDemo的类

    编写代码时未报错,点击运行,运行结果如下,报异常:

    2、使用try/catch捕捉异常

    package introduction8;
    
    public class RuntimeExceptionDemo {
    
        public static void main(String[] args) {
            
            int a = 10;
            int b = 0;
            int c;
            try {
            c = a/b;
            System.out.println("计算结果为:"+c);
            }catch(ArithmeticException e) {
                System.out.println(e.getMessage());
            }
        }
    
    }

    运行结果:

    二、案例演示(角标越界运行时异常)

     

    运行结果:

    使用try/catch捕捉异常

    package introduction8;
    
    public class RuntimeExceptionDemo {
    
        public static void main(String[] args) {
        /*
        //除数为0
            int a = 10;
            int b = 0;
            int c;
            try {
            c = a/b;
            System.out.println("计算结果为:"+c);
            }catch(ArithmeticException e) {
                System.out.println(e.getMessage());
                System.out.println("0不能为除数");
            }
        */    
        //角标越界
            int[] numbers = {1,2,3};
            try {
                for(int i = 0;i<=3;i++) {
                    System.out.println(numbers[i]);
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println("角标"+e.getMessage()+"越界情况");
            }
            
        }
    
    }
  • 相关阅读:
    一起学Python:协程
    一起学Python:字符串介绍
    一起学Python:列表介绍
    一起学Python:字典介绍
    一起学Python:元组
    函数介绍
    函数参数和函数返回值
    CodeForces 680A&680B&680C&680D Round#356
    POJ 3481 set水过
    BZOJ 1037 生日聚会 DP
  • 原文地址:https://www.cnblogs.com/luohuasheng/p/9662279.html
Copyright © 2011-2022 走看看