zoukankan      html  css  js  c++  java
  • Java 基础(自定义异常)

    如何自定义异常类?

    1. 继承于现有的异常结构: RuntimeException, Exception
    2. 提供全局常量: serialVersionUID
    3. 提供重载的构造器

    throw 和 throws 区别:
    throw 表示抛出一个异常类的对象,生成异常对象的过程。声明在方法体内。
    throws 属于异常处理的一种方式,声明在方法的声明处。

    MyException.java

    package com.klvchen.java2;
    
    public class MyException extends RuntimeException {
    	
    	static final long serialVersionUID = -7034897190745766999L;
    	
    	public MyException() {}
    	
    	public MyException(String msg) {
    		super(msg);
    	}
    
    }
    

    StudentTest.java

    package com.klvchen.java2;
    
    public class StudentTest {
    	public static void main(String[] args) {
    		Student s = new Student();
    		try {
    			s.regist(-100);
    		} catch (Exception e) {
    //			e.printStackTrace();
    			System.out.println(e.getMessage());
    		}
    	}
    	
    }
    
    
    class Student{
    	
    	private int id;
    	
    	public void regist(int id) throws Exception{
    		if(id > 0) {
    			this.id = id;
    		}else {
    			throw new MyException("不能输入负数");
    		}
    	}
    	
    	public String toString() {
    		return "Student [id=" + id + "]";
    	}
    }
    

  • 相关阅读:
    JOIN条件限制对结果记录的影响
    什么是linux?
    什么是操作系统?
    Internship settled!
    Python dict 调试技巧 —— 利用YAML存储dict内容
    c++ 异常处理
    C#可空类型
    C# 异常处理
    C#值类型与引用类型
    C# 类类型
  • 原文地址:https://www.cnblogs.com/klvchen/p/14578469.html
Copyright © 2011-2022 走看看