自定义异常 java

Custom Exceptions or User-Defined Exceptions are very common in Java applications. We can easily create custom exception classes for different use cases.

自定义异常或用户定义的异常在Java应用程序中非常常见。 我们可以轻松地为不同用例创建自定义异常类。



有哪些不同类型的例外? (What are the different types of Exceptions?)

In Java, there are two categories of Exceptions:

在Java中,有两类异常:

  • Checked Exceptions – These are recoverable. These are derived from the Exception class. For example, IOException and FileNotFoundException are checked exceptions.已检查的异常 –这些是可恢复的。 这些是从Exception类派生的。 例如,IOException和FileNotFoundException是已检查的异常。
  • Unchecked Exceptions – These are not recoverable and occur at runtime. These are derived from java.lang.RuntimeException class. For example, NullPointerException and IllegalArgumentException are unchecked exceptions.未检查的异常 –这些不可恢复的异常在运行时发生。 这些是从java.lang.RuntimeException类派生的。 例如, NullPointerException和IllegalArgumentException是未经检查的异常。

Further Reading: Exception Handling in Java.

深度阅读 : Java中的异常处理 。

Moving ahead, let’s look at custom exceptions in the next section.

继续前进,让我们在下一部分中查看自定义异常。



Java自定义异常或用户定义的异常 (Java Custom Exceptions or User-Defined Exceptions)

Custom Exceptions are user-defined exceptions. These are written by programmers specifically for there application use cases.

自定义异常是用户定义的异常。 这些是由程序员专门为那里的应用程序用例编写的。

Exception or its child classes.Exception或其子类。

Unchecked custom exception extends RuntimeException or its child classes.

未经检查的自定义异常扩展了RuntimeException或其子类。

All Exceptions are a child of Throwable.

所有异常都是Throwable的子级。

Before we get down to the implementation part, let’s make note of a few points.

在介绍实现部分之前,让我们注意一些要点。

  • Create Custom Exceptions only when they provide a specific use case that none of the available Exceptions provide.仅当自定义异常提供了可用异常均不提供的特定用例时,才创建自定义异常。
  • All custom exceptions must follow the standard naming convention. That is camel case and ending with the word “Exception”.所有自定义例外都必须遵循标准命名约定。 那是骆驼的情况,并以“例外”一词结尾。
  • Use overloaded constructors for all scenarios.在所有情况下都使用重载的构造函数。


1.自定义未经检查的异常 (1. Custom Unchecked Exceptions)

An example of custom unchecked exceptions is given below.

自定义未检查的异常示例如下。

package com.journaldev.java;import java.util.ArrayList;public class CustomExceptions {public static void main(String[] args) {ArrayList<String> arrayList = new ArrayList<>();arrayList.add("Monday");arrayList.add("Tuesday");arrayList.add("Wednesday");String day = "Sunday";if (!arrayList.contains(day)) {try {throw new DayNotAvailableException("Day not available",day);} catch (DayNotAvailableException e) {e.getLocalizedMessage();e.printStackTrace();}}}
}class DayNotAvailableException extends RuntimeException {private String day;public DayNotAvailableException() {super();}public DayNotAvailableException(String message, String day) {super(message);this.day = day;}public DayNotAvailableException(String message, String day, Throwable cause) {super(message, cause);this.day = day;}@Overridepublic String toString() {return super.toString();}@Overridepublic String getMessage() {return super.getMessage() + " for the day :" + day;}@Overridepublic String getLocalizedMessage() {return "The day "+day + " is not available.";}
}

Java Custom Unchecked Exception

Java自定义未经检查的异常

In the above program, we simply throw an error when the value is not present in the ArrayList.

在上面的程序中,当ArrayList中不存在该值时,我们只是抛出一个错误。

In the custom exception, we have defined multiple constructors to cover different cases.

在自定义异常中,我们定义了多个构造函数以涵盖不同的情况。

The getMessage() and getLocalisedMessage() are overridden to provide custom responses.

getMessage()和getLocalisedMessage()被重写以提供自定义响应。



2.用户定义的检查异常 (2. User-Defined Checked Exception)

Here is a simple example of user-defined checked exception. We will extend the Exception class and override the toString() method.

这是用户定义的检查异常的简单示例。 我们将扩展Exception类并重写toString()方法。

package com.journaldev.java;public class EmployeeNotFoundException extends Exception {private static final long serialVersionUID = -2872694086602732648L;private int id;EmployeeNotFoundException(int i, String message) {super(message);this.id = i;}EmployeeNotFoundException(int i, String message, String cause) {super(message, new Throwable(cause));this.id = i;}@Overridepublic String toString() {return String.format("EmployeeNotFoundException[%d]", this.id);}}

结论 (Conclusion)

Summing up, Custom Exceptions behave like built-in Exception types. Create a custom exception whenever you need to handle your application/module specific exceptions and boundaries.

总结起来,自定义异常的行为类似于内置的异常类型。 每当需要处理应用程序/模块特定的异常和边界时,都创建一个自定义异常。

翻译自: https://www.journaldev.com/31560/java-custom-exception-user-defined

自定义异常 java

自定义异常 java_Java自定义异常–用户定义的异常相关推荐

  1. Oracle入门(十四.16)之捕获用户定义的异常

    一.异常类型 本文讨论用户定义的错误. 二.捕获用户定义的异常 PL / SQL允许你定义你自己的异常. 您根据应用程序的要求定义异常. 输入数据期间需要用户定义的异常的一个示例. 假设您的程序提示用 ...

  2. 【Oracle】ORA-06510: PL/SQL: 用户定义的异常错误未得到处理

    异常除了定义,还需要有代码块去处理异常. 详见参考文章:https://www.techonthenet.com/oracle/errors/ora06510.php

  3. python自定义异常_Python自定义异常

    python自定义异常 In this tutorial we are going to learn about Python Custom Exception. If you don't know ...

  4. java抛出自定义异常_10 个深恶痛绝的 Java 异常。。

    异常是 Java 程序中经常遇到的问题,我想每一个 Java 程序员都讨厌异常,一 个异常就是一个 BUG,就要花很多时间来定位异常问题. 什么是异常及异常的分类请看这篇文章:一张图搞清楚 Java ...

  5. udt java_Java DB中的Java用户定义类型(UDT)

    udt java Java DB是基于Java编程语言和SQL的关系数据库管理系统. 这是Apache软件基金会的开源Derby项目的Oracle版本. Java SE 7 SDK中包含Java DB ...

  6. 抛出异常及声明异常 自己定义一个异常

    抛出异常用throw关键字同时只能抛出一个异常.抛出异常的时候有两种选择  直接try-catch抓取还有就是底层不解决异常,底层往上抛,在顶层解决异常,异常在底层表现不容易被顶层发现 java中通过 ...

  7. 检测用户中的异常--UEBA方法

    Detecting Anomalies in Users – An UEBA Approach 检测用户中的异常–UEBA方法 期刊/会议:Proceedings of the Internation ...

  8. CodeGen用户定义的扩展令牌

    CodeGen用户定义的扩展令牌 用户定义的扩展令牌是一种特殊的令牌,开发人员可以确定令牌的名称以及在代码生成过程中遇到令牌时要插入的值. CodeGen支持多种机制,允许通过以下方式实现用户定义的令 ...

  9. java linkedlist排序_用Java对用户定义对象的LinkedList进行排序

    要使用Java对列表进行排序,可以使用sort(List list) 方法.此方法可以对所有元素必须实现Comparable接口的列表进行排序. 在下面的示例中,House类是用户定义的.为了使其具有 ...

最新文章

  1. 微信小程序客服实现自动回复图文消息链接,点击去关注公众号
  2. 小型工作室创业项目_为什么新开发人员应该在小型创业公司工作
  3. 6条可以成为更好程序员的建议
  4. matlab考试湖北理工学院,电子信息工程导论课程教学大纲-电气与电子信息工程学院-湖北.DOC...
  5. 2021-10-20开发计量系统遇到的问题之--1启动mysql--2mybatis谨慎注释--3mybatis返回多表查询结果
  6. 语音增强原理之噪声估计
  7. 今日头条|张一鸣:我遇到的优秀年轻人的5个特质
  8. 区块链 | 基础链 ICO 白皮书分析
  9. c++ 多重背包状态转移方程_【考前再叮嘱】陌生方程式书写
  10. 注册表文件(*.reg)的编写及应用
  11. 华为面试分配_什么时候不做面试分配
  12. Linux设备树 .dtb文件,内核使用dtb文件的过程
  13. AI芯片、框架、语言与知识、量子计算……百度大脑6.0发布
  14. POJ3155 Hard Life
  15. diff与patch操作
  16. 韦东山《嵌入式Linux应用开发完全手册》配套视频教程
  17. 北斗广播星历和精密星历的下载
  18. usboot应用两篇:用USBOOT修理移动硬盘等
  19. 混合非线性整数规划matlab,非线性整数规划matlab
  20. qq游戏大厅中解析不安装apk的研究

热门文章

  1. 我要好offer之 二叉树大总结
  2. LLVM每日谈之三 如何创建一个LLVM工程
  3. 四六级英语都考过,让你见识一下“八级程序员”
  4. UVALive 4212 Candy
  5. ORALCE 两表结构更新
  6. [转载] python win32api 使用小技巧
  7. 建立时间和保持时间关系详解
  8. JSP学习 三大指令、九个内置对象、JavaBean、EL表达式
  9. 基于WF的意见征集6(浅析)
  10. opencv-contrib-Python编译module ‘cv2.cv2‘ has no attribute ‘xfeatures2d‘