or123456
or123456

Reputation: 2199

Get All Exceptions in a Java Application

how to get all Exceptions in a java application (have several classes and packages) in a place? Example: create a class be get all Exceptions on other application classes

Upvotes: 1

Views: 14750

Answers (5)

Agustin Catalano
Agustin Catalano

Reputation: 59

You can use:

try {

//  block of code ...

} catch (Exception e){

// Do something with e

}

Upvotes: 0

Robin
Robin

Reputation: 36621

As other already indicated, one option is to put your main method in a try-catch block

public static void main( String[] args ){
  try{
    //regular main code
  } catch (Throwable e){
    //do exception handling
  }
}

Another possibility is setting a default uncaughtExceptionHandler on the Thread(s) you are using with the Thread#setDefaultUncaughtExceptionHandler method.

Note that both solutions only allow you to 'handle all exceptions in one place' if they don't get caught at other locations in your application

Upvotes: 3

st0le
st0le

Reputation: 33575

Why don't you simply have a class ExceptionHandler with 2 functions

void handleException(Exception e);
void handleThrowable(Throwable t);

and at every try{}catch(Exception e){} simply use ExceptionHandler.handleException(e);

To find out what Exception is being thrown, use instanceof

For eg.

if(e instanceof NullPointerException)
{
//whatver
}

Upvotes: 1

Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

If all you methods throw exception to the main calling method then you can catch all exceptions.

The hierarchy of exception classes commence from Throwable class which is the base class for an entire family of exception classes, declared in java.lang package as java.lang.Throwable.

Upvotes: 0

Ramon Saraiva
Ramon Saraiva

Reputation: 518

In your main class, you may have something like this:

try { } catch (Exception ex) { }

In your other classes, you should throw the exceptions, like:

public void example() throws Exception { }

If you throw the other classes' exceptions, you can deal with them just in the main class.

Upvotes: 0

Related Questions