Home > Mobile >  how do i print only the exception name in java instead of complete name?
how do i print only the exception name in java instead of complete name?

Time:11-28

how do i print only the exception name in java instead of complete name ?

for e.g IllegalArgumentException exception -

it return exception --

java.lang.IllegalArgumentException: some message

but i want to return only this -

IllegalArgumentException: some message

CodePudding user response:

If you have a Class object you can call getSimpleName().

    Class cls = Integer.class;
    System.out.println(cls.getSimpleName());

CodePudding user response:

For your own custom exceptions you can override toString() to format return value.

For exceptions from the standard library and other frameworks you may want to have a method which looks something like this:

void formatExceptionMessage(Exception ex) {
    System.out.println(ex.getClass().getSimpleName()   ": "   ex.getMessage());
}

You could place this in a class where you have other utility methods and call it whenever you catch an exception.

CodePudding user response:

public static void main(String[] args) {
        try {
            throw new IllegalArgumentException("Some message");
        }catch (Exception exception){
            System.out.println(String.format("%s: %s",exception.getClass().getSimpleName(),exception.getMessage()));
        }
    }

Output:

IllegalArgumentException: Some message
  • Related