shubham patil
shubham patil

Reputation: 1

supress Java checked Exception

I have writen the following code. I know it might not be the correct approach. but this is what i have done.

public class ValidationRule {
    private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
    private static Date afterdt = sdf.parse("1/4/2021");
    private static Date beforedt = sdf.parse("1/4/2025");

in the lines parse function throws "ParseException". I want to know if there is any way to suppress the exception somehow. and make this work.that is my main question. if you can also suggest any smarter approaches to initiate a date var , i would really appriciate it.

public class ValidationRule {
    private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
    private static Date afterdt = sdf.parse("1/4/2021");
    private static Date beforedt = sdf.parse("1/4/2025");
    
    public static Date validateDate(String dts) throws ParseException, DateNotRightException {
        
        Date dt = sdf.parse(dts);
        if(dt.after(afterdt)) {
            throw new DateNotRightException("date too early");
        }
        else if(dt.before(beforedt)) {
            throw new DateNotRightException("date too farrrr");
        }
        
        return dt;
        
    }

this is just a stupid code i am writing to learn concepts.

Upvotes: -1

Views: 80

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201517

You could use a static initializer block to initialize your static fields. That way you can have a try-catch to cover your initialization. Like,

private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY");
private static Date afterdt = null;
private static Date beforedt = null;
static {
    try {
        afterdt = sdf.parse("1/4/2021");
        beforedt = sdf.parse("1/4/2025");
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
}

Upvotes: 1

Related Questions