• JAVA_SE基础——55.自定义异常类


    在Java中已经提供了大量的异常类,但是这些异常类有时野很难满足开发者的要求,所以用户可以根据自己的需要来定义自己的异常类。但自定义的异常类必须继承自Exception或其子类。


    可以自定义出的问题称为自定义异常。对于除数为0的情况,可以用ChuShu0异常来表示,除数为0这种异常在java中并没有定义过。那就按照java异常的创建思想,面向对象,将除数为0进行自定义描述,并封装成对象。这种自定义的问题描述称为自定义异常。


    code1中体现自定义类继承Exception或者其子类,通过构造函数定义异常信息。

    code1

    Class ChuShu0 extends Exception{
         DemoException(String message){
              super(message);//调用Exception有参的构造方法
         }
    }

    在实际开发中  如果没有特殊要求,自定义的异常类只需继承Exception类,在构造方法中使用super()语句调用Exception的构造方法即可。

    既然定义了 自定义的异常类 ,那么怎么使用呢? 其实使用方法和Exception类及其子类是一样的用法的,还是那2种处理方式。


    code2中体现下面来看下除数为0的异常演示

    code2

    package day10;
    class ChuShu0Exception extends Exception{
    	public ChuShu0Exception(String msg){
    		super(msg);
    	}
    }
    public class TestException3  {
    	
    	public static void main(String[] args){
    		try{
    			int result = divide(4,0);
    			System.out.println(result);
    		}catch(Exception e){
    			e.printStackTrace();
    		}
    	}
    	public static int divide(int a , int b ) throws Exception {
    		if(b==0){
    			throw new ChuShu0Exception("除数为0");
    		}
    		int result = a/b ;
    		return result ;
    	}
    }

    运行结果:

    day10.ChuShu0Exception: 除数为0
    at day10.TestException3.divide(TestException3.java:19)
    at day10.TestException3.main(TestException3.java:11)


    P.S.

    code3中体现如果自定义类继承的是RuntimeException,那么运行时异常的特点是Java编译器不会对其进行检查,也就是说,当程序中出现这类异常时,既没有受用try...catch语句捕获或使用throws关键字声明抛出,程序也能编译通过,如果有异常产生,则异常将由JVM进行处理(继续往上抛,直至抛给JVM)


    code3

    package day10;
    class ChuShu0Exception extends RuntimeException{
    	public ChuShu0Exception(String msg){
    		super(msg);
    	}
    }
    public class TestException3  {
    	
    	public static void main(String[] args){
    		//try{
    			int result = divide(4,0);
    			System.out.println(result);
    		//}catch(Exception e){
    		//	e.printStackTrace();
    		//}
    	}
    	public static int divide(int a , int b ){
    		if(b==0){
    			throw new ChuShu0Exception("除数为0");
    		}
    		int result = a/b ;
    		return result ;
    	}
    }
    运行结果:

    Exception in thread "main" day10.ChuShu0Exception: 除数为0
    at day10.TestException3.divide(TestException3.java:19)
    at day10.TestException3.main(TestException3.java:11)



    交流企鹅:654249738,和自学者交流群:517284938


  • 相关阅读:
    Python进阶之浅谈内置方法(补充)
    Python进阶之浅谈内置方法
    Python运算符优先级
    python之浅谈循环
    MTCNN
    MTCNN
    tf.train.batch and tf.train.shuffle_batch
    tf.add_to_collection 和 tf.get_collection 和 tf.add_n
    tensorflow 迁移学习-Demo
    tensorflow 加载预训练模型进行 finetune 的操作解析
  • 原文地址:https://www.cnblogs.com/Jhaiha0/p/8465286.html
Copyright © 2020-2023  润新知