Friday 24 January 2020

Eclipse: Enable break point when exception thrown


You can enable debug point when a specific exception thrown by the application.

Let’s see it with an example.

App.java
package com.sample.app;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class App {

 public static void main(String[] args) {

  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  System.out.println("Enter an Integer");
  try {
   int i = Integer.parseInt(br.readLine());
   System.out.println(i);
  } catch (NumberFormatException | IOException e) {

   e.printStackTrace();
  }

 }

}

As you see above application, it is requesting user to enter an integer. If user enter an integer, then the application exists successfully. If user enters any non-integer, then application exits by throwing NumberFormatException.

How to enable break point for NumberFormatException?
Open Debug perspective.


Window -> Perspective -> Open Perspective -> Debug.


Go to the breakpoints window, there's a button that looks like J!, there you can set breakpoints for Java exceptions.


Click on J! button.

It opens ‘Add Java Exception Breakpoint’.


Select NumberFormatException and click on OK button.



You can confirm the that NumberFormatException is added in Breakpoints window.

Run the application in debug mode
Right click on application source code -> Debug As -> Java Application.

Application prompts you to ‘Enter an Integer’. Enter any string  (non number) as input.


Once you enter non number input, you can observe that control stops at the line where NumberFormatException is getting thrown.


You may like
Previous                                                    Next                                                    Home

No comments:

Post a Comment