tareviverat
tareviverat

Reputation: 57

Avoiding nested try/catch

import java.util.Scanner;

public class Test{

    public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    String str = input.next();
    int a;
    try{
        try{
            a = Integer.parseInt(str);
        }
        catch(NumberFormatException nfe){
            throw new CustomException("message");
        }
        if (a>50) throw new CustomException("message");
    }
    catch(CustomException e){
        //do something
    }
}
}

If str is something other than numbers, parseInt will throw a NumberFormatException. But I want to 'convert' it so that I'll have a CustomException with "message" instead. Can I do this without using a nested try/catch blocks like above?

Upvotes: 2

Views: 2034

Answers (3)

user902383
user902383

Reputation: 8640

you could refator your example to

 try {
     a = Integer.parseInt(str);
     if (a > 50) {
         throw new CustomException("message");
     }
 } catch (NumberFormatException | CustomException e){
     //do something
 }

Upvotes: 2

Arye Shemesh
Arye Shemesh

Reputation: 679

Use the Scanner.hasNextInt() to parse the int without worrying about exceptions.

see this question for detailed code.

Upvotes: 1

Andrea Iacono
Andrea Iacono

Reputation: 802

You could write:

public static void main(String[] args){

    Scanner input = new Scanner(System.in);
    String str = input.next();
    int a;
    try{
        a = Integer.parseInt(str);
        if (a>50) throw new NumberFormatException("message");
    }
    catch(NumberFormatException e){
        //do something
    }
}

but I suggest you to use your version, since the code is more readable. My version, even if removes the inner try, is less readable than yours.

Upvotes: 0

Related Questions