处理方法异常的正确方法?

Correct way to handle method exception?

我似乎对如何抛出异常以及何时使用它来创建自己的异常感到有点困惑。

我有这段代码,想知道我是否以正确的方式处理这个问题

方法如下:

public void setHireYear(int year) throws Exception {
    try{
        if (year <= CURRENT_YEAR && year >= CURRENT_YEAR - MAX_YEARS_WORKED) {
            hireYear = year;
        }
        else{
            throw new HireYearException(year);
        }
    }catch(HireYearException e){
        e.toString();
    }
}

这里是例外 class:

public class HireYearException extends Exception
{

private int hireYear;

/**
 * Constructor for objects of class HireYearException
 */
public HireYearException(int hireYear)
{
   this.hireYear = hireYear;
}


public String toString()
{
   return "Hire year cannot exceed Current year, your hire year is - " + hireYear;
}
}

为什么抛出自定义异常比抛出预定义异常更好?

特定的海关例外允许您为您的 catch 语句分离不同的错误类型。异常处理的通用构造是这样的:

try
{}
catch (Exception ex)
{}

这会捕获所有类型的异常。但是,如果您有自定义异常,则可以为每种类型设置单独的处理程序:

try
{}
catch (CustomException1 ex1)
{
    //handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
    //handle CustomException2 type errors here
}
catch (Exception ex)
{
    //handle all other types of exceptions here
}

因此它为您提供(好处以及创建它的原因)

1.specific 异常允许您更好地控制异常处理

2.Provides 开发人员检测错误情况的类型安全机制。

3.Add 特定情况数据异常 理想情况下,此数据将帮助其他开发人员追踪错误的来源。

4.No 现有异常充分描述了我的问题

Source