自定义异常 java_Java自定义异常–用户定义的异常

自定义异常 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;
    }

    @Override
    public String toString() {
        return super.toString();
    }

    @Override
    public String getMessage() {
        return super.getMessage() + " for the day :" + day;
    }

    @Override
    public String getLocalizedMessage() {
        return "The day "+day + " is not available.";
    }
}
Java Custom Checked Exceptions

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;
	}

	@Override
	public 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值