抛出异常与使用 switch 语句返回空值 [英] Throwing exception vs returning null value with switch statement

查看:61
本文介绍了抛出异常与使用 switch 语句返回空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有格式化日期以强制给定枚举 DateType{CURRENT, START, END} 的函数在使用 switch 语句的情况下处理返回值的最佳方法是什么

So I have function that formats a date to coerce to given enum DateType{CURRENT, START, END} what would be the best way to handling return value with cases that use switch statement

public static String format(Date date, DateType datetype) {
    ..validation checks

    switch(datetype){
    case CURRENT:{
        return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
    }               
    ... 
     default:throw new ("Something strange happend");
    }

}

OR 在最后抛出异常

   public static String format(Date date, DateType datetype) {
            ..validation checks

            switch(datetype){
            case CURRENT:{
                return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
            }               
            ... 
            }

               //It will never reach here, just to make compiler happy 
        throw new IllegalArgumentException("Something strange happend");    
        }

或返回空

public static String format(Date date, DateType datetype) {
            ..validation checks

            switch(datetype){
            case CURRENT:{
                return getFormattedDate(date, "yyyy-MM-dd hh:mm:ss");
            }               
            ... 
            }

             return null;   
}

这里的最佳做法是什么?此外,所有枚举值都将在 case 语句中处理

What would be the best practice here ? Also all the enum values will be handled in the case statement

推荐答案

抛出异常,因为这是一个例外情况.

Throw an exception, since this is an exceptional case.

把它扔到switch之外,它会更易读.否则听起来像是默认情况是例外".

And throw it outside the switch, it would be more readable. Otherwise it sounds like "the default case is exceptional".

这篇关于抛出异常与使用 switch 语句返回空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆