如何在JAVA中的差异原因对象上为相同的NumberFormatException打印差异消息? [英] How to print diff Msg for same NumberFormatException on diff cause objects in JAVA?

查看:85
本文介绍了如何在JAVA中的差异原因对象上为相同的NumberFormatException打印差异消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

How to print diff Msg for same NumberFormatException on diff cause objects in JAVA?

try {  int a=Integer.parseInt(aStr); int b= Integer.parseInt(bStr); }catch (NumberFormatException ex) {   if ex's cause is from int a;//ex.getCause()=a? System.out.println("a is not a integer");   if ex's cause is from int b System.out.println("b is not a integer"); }



尝试{int a = Integer.parseInt(aStr); int b = Integer.parseInt(bStr); } catch(NumberFormatException ex){如果ex的原因是来自int a;//ex.getCause()= a? System.out.println("a不是整数");}
catch(NumberFormatException ex){如果ex的原因来自int b System.out.println("b不是整数"); }



try { int a=Integer.parseInt(aStr); int b= Integer.parseInt(bStr); }catch (NumberFormatException ex) { if ex''s cause is from int a;//ex.getCause()=a? System.out.println("a is not a integer");}
catch (NumberFormatException ex){ if ex''s cause is from int b System.out.println("b is not a integer"); }

推荐答案

我会将整个内容包装在一个辅助方法中,如下所示:

I would wrap that whole thing up in a helper method, like this:

package com.test;

import java.text.ParseException;

public class Program {

  private static int CheckIntegerArgument(String value, String name) {
    try {
      return Integer.parseInt(value);
    }
    catch(NumberFormatException e) {
      throw new 
        IllegalArgumentException(String.format("%s is not a number (%s)", name, value));
    }
  }

  public static void someMethod(String a, String b) {
    int aValue =  CheckIntegerArgument(a, "a");
    int bValue =  CheckIntegerArgument(b, "b");

    // Use aValue and bValue here;
  }

  public static void main(String[] args) throws Exception, ParseException {
    try {
      someMethod("1234", "I am not a number");
    }
    catch(IllegalArgumentException e) {
      System.out.println(e.getMessage());
    }
  }
}



希望这会有所帮助,
弗雷德里克·博纳德(Fredrik Bornander)



Hope this helps,
Fredrik Bornander


这篇关于如何在JAVA中的差异原因对象上为相同的NumberFormatException打印差异消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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