简体   繁体   中英

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?

you could refator your example to

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

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

see this question for detailed code.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM