views:

280

answers:

4

HiAll,

Can anyone explain how to handle the runtime exceptions in Java?

Thanks, Ravi

+4  A: 

It doesn't differ from handling a regular exception:

try {
   someMethodThatThrowsRuntimeException();
} catch (RuntimeException ex) {
   // do something with the runtime exception
}
Bozho
can catch the runtime exceptions..?
Ravi K Chowdary
Of course! All subclasses of `Throwable` can be caught.
Carl Smotricz
A: 

If you know the type of Exception that might be thrown, you could catch it explicitly. You could also catch Exception, but this is generally considered to be very bad practice because you would then be treating Exceptions of all types the same way.

Generally the point of a RuntimeException is that you can't handle it gracefully, and they are not expected to be thrown during normal execution of your program.

danben
A: 

You just catch them, like any other exception.

try {
   somethingThrowingARuntimeException()
}
catch (RuntimeException re) {
  // Do something with it. At least log it.
}
Confusion
A: 

Not sure if you're referring directly to RuntimeException in Java, so I'll assume you're talking about run-time exceptions.

The basic idea of exception handling in Java is that you encapsulate the code you expect might raise an exception in a special statement, like below.

try {
   // Do something here
}

Then, you handle the exception.

catch (Exception e) {
   // Do something to gracefully fail
}

If you need certain things to execute regardless of whether an exception is raised, add finally.

finally {
   // Clean up operation
}

All together it looks like this.

try {
   // Do something here
}
catch (Exception e) {
}
catch (AnotherException ex) {
}
finally {
}
Ed Altorfer
can we catch the runtime exception? How it is possible? with out knowing the runtime exception, how we catch it programatically?
Ravi K Chowdary
You can use `catch (ExceptionType name) {}` to catch any type of exception. Otherwise, you can use `catch {}` to catch all exceptions, or `catch (Exception name) {}` to catch all exceptions (and have the information about them accessible to you.
Ed Altorfer
@Ed: It is correct.But if i got error on the server(loading issue).this is runtime exception.How we will catch this exception programatically? is it possible?
Ravi K Chowdary
I don't know what you mean...you catch exceptions programmatically using the syntax I gave you.
Ed Altorfer