Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exception vs returning null value with switch statement

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 throw excpetion at the end

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

OR return null

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

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

like image 530
Greg Avatar asked Apr 02 '10 16:04

Greg


2 Answers

Throw an exception, since this is an exceptional case.

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

like image 198
Bozho Avatar answered Oct 12 '22 18:10

Bozho


I think that throw new IllegalArgumentException("Something strange happend") is the best pratice.

Using null will just presumibly cause a NullPointerException somewhere when you use the return value but it will be less informative than raising a specific exception that describes the problem!

And you know: clear errors = better developing.

like image 21
Jack Avatar answered Oct 12 '22 18:10

Jack