Click here to Skip to main content
15,920,217 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
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"); }


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

1 solution

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

Java
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());
    }
  }
}


Hope this helps,
Fredrik Bornander
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900