zoukankan      html  css  js  c++  java
  • 抛出异常

     抛出异常有两种方式:

    1.程序中抛出异常

    在程序中抛出异常要用关键字throw,throw抛出的是一个异常类的实例对象

    语法

    throw 异常类实例对象;

    例程序抛出异常

    package ch01;
    
    public class ep3_3 {
        public static void main(String args[]){
            int a=2,b=0;
            try{
                if(b==0)
                    throw new ArithmeticException("算术异常");
            else
                System.out.println(a+"/"+b+"="+a/b);
            }catch(ArithmeticException e){
                System.out.println("抛出异常"+e);
            }
        }
    
    }

    执行结果

    抛出异常java.lang.ArithmeticException: 算术异常

    2.指定方法抛出异常

    如果方法内程序可能发生异常而且方法内没有使用任何代码来捕获异常则需要在声明方法时指明可能发生的所有异常,以便让调用此方法的程序做好准备捕获异常(如果方法会抛出异常则可以将处理此异常的try-catch()-finally块写在调用此方法的代码内)

    语法

    方法名称(参数···) throw 异常类1,异常类2 

    例方法抛出异常

    class test
    {
        //throw 在指定的方法中不处理异常在调用方法的地方处理
        void add(int a,int b) throws Exception{
            int c;
            c=a/b;
            System.out.println(a+"/"+b+"="+a/b);
            
        }
    }
    public class ep3_4 {
        
    
        public static void main(String args[]){
            test t=new test();
            try {
                t.add(4, 0);
            } catch (Exception e) {
                
                e.printStackTrace();
            }
            
        }
    
    }
  • 相关阅读:
    CodeForces 7B
    CodeForces 4D
    离散化
    线段树入门
    洛谷 P3951 小凯的疑惑(赛瓦维斯特定理)
    Codeforces 1295D Same GCDs (欧拉函数)
    Codeforces 1295C Obtain The String (二分)
    Codeforces 1295B Infinite Prefixes
    Codeforces 1295A Display The Number(思维)
    Codeforces 1294F Three Paths on a Tree(树的直径,思维)
  • 原文地址:https://www.cnblogs.com/gc56-db/p/6877656.html
Copyright © 2011-2022 走看看