Wednesday, May 9, 2018

Is it possible to catch out of memory error [OutOfMemoryError] in java?

Yes !! You can catch OutOfMemoryError as it descends from Throwable class.
  1. public void run() {
  2. try {
  3. System.out.println("out of memory error occured");
  4. } catch (OutOfMemoryError e) {
  5. System.out.println("Out of memory error handled");
  6. }
  7. }
In this case we may not know where the memory leak will happen. thus there is no use of catch block to handle OutOfMemoryError. better increase the heap size by using the flag -Xmx (-Xmx2048M) in project's configuration
  • Is it possible to handle exception using OutOfMemoryError in java?
No !! Since, exceptions can be handled using Exception type object not error type object because OutOfMemoryError is error type object. If we really wants to handle any type of error or exception we must make use of Throwable

example:-
  1. public static void run() {
  2. try {
  3. int a = 10 / 0;
  4. System.out.println("out of memory error occured" + a);
  5. } catch (OutOfMemoryError e) {
  6. System.out.println("Out of memory error handled");
  7. }
  8. }

Output: Exception in thread "main" java.lang.ArithmeticException: / by zero
  1. public static void main(String[] args) {
  2. run();
  3. }
  4. public static void run() {
  5. try {
  6. int a = 10 / 0;
  7. System.out.println("out of memory error occured" + a);
  8. } catch (Throwable e) {
  9. System.out.println("Out of memory error handled");
  10. }
  11. }
Output: Out of memory error handled

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...