安卓如何在Java中管理多个自定义异常
让我解释一下我在java 安卓中做了什么
方法1:
我定义了三个自定义异常
Public class invalidEmpIDException extends Exception{
public Integer empID;
public MyExceptionONE(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}
}
Public class invalidPermissionEception extends Exception{
public Integer empID;
public MyExceptionTWO(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}
}
Public class MyExceptionTHREE extends Exception{
public Integer empID;
public MyExceptionONE(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}
}
注意:
编写的函数在大多数情况下都需要抛出不同条件下的所有三个异常强>
例如:
public myfunction throws invalidEmpIDException ,invalidPermissionEception, MyExceptionTHREE
{
// My Code here..
// On some condition throws invalidPermissionException,
// on Some condition throws invalidEmpIDException,
// on Some cndition throws MyExceptionTHREE..
}
现在消费者写道:
try {
myfunction
}
catch ( invalidEmpIDException e)
{
}
catch ( invalidPermissionException e)
{
}
catch ( MyExceptionTHREE e)
{
}
起初我觉得这种方法还可以,但当情况出现时 如果用户需要在很多地方调用“myfunction”,那么代码就会变得笨拙。因此我尝试了下面的方法
catch ( invalidEmpIDException | invalidPermissionException | MyExceptionTHREE ex ) {
ex.getEmpID()
}
问题-1:无法解决此getEmpID()
从我找到的搜索中,可以通过引入从Exception继承的BaseClasseException,然后引入从BaseClasseException继承的所有其他子类来解决上述问题
因此,
public Class BaseException extends Exception
{
public Integer empID;
public BaseException(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}
}
}
public Class invalidEmpIDException extends BaseException
{
public invalidEmpIDException(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}}
public Class invalidPermissionException extends BaseException
{
public invalidPermissionException(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}}
}
public Class MyExceptionTHREE extends BaseException
{
public MyExceptionTHREE(Integer id) {
this.empID = id;
}
public Integer getEmpID () {
return this.empID;
}}
}
上述方法解决了我的问题1,但导致了下面解释的另一个问题
问题:
1)在invaliePermissionException子类中定义一个新方法,该方法仅适用于此类
Example:
public Integer getUserCode() {
}
2)现在如何在catch块中使用特定于invalidPermissionException的access getUserCode
catch ( invalidEmpIDException | invalidPermissionException | MyExceptionTHREE ex ) {
ex.getEmpID()
}
如果我需要改变我的方法,请告诉我,因为这是我第一次尝试在java中处理异常
# 1 楼答案
使用multi-catch的方法是有效的,因为
ex
将是所有异常都具有的最常见的类型。在您的情况下,它将是BasicException
。如果您想对不同的异常执行不同的操作,您应该使用单独的catch块返回到第一种方法,因为您无法访问自定义异常类中定义的每个特定方法正如Jägermeister statet所说,另一种方法可以是使用抽象类,这样您只需要调用
createExceptionMessage
,并使您的其他异常创建此方法的实现