• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

Anything like C/C++ _LINE_ in JAVA ?

Does anyone have any code that will do what the _LINE_ in C/C++ does when logging messages?

Thanks in advance !
  • 2
1 Solution
jefftkAuthor Commented:
Adjusted points to 100
The line number is contained in a stack trace which gets generated when the exception is thrown (if the code is compiled in debug mode). Can you simply print a stack trace if something happens (otherwise why do you need a line number)?
jefftkAuthor Commented:
I am trying to simulate the C/C++ environment...
There are _FILE_ and _LINE_  macros the supply the program name and line number to the logging facility...
There isn't a direct macro to give you the file and line numbers. If you're into kludges, however, you can do the following:

1. throw an exception
2. catch it
3. capture the stack trace in a string
4. parse it to get the file and line number

Here are steps 1-3:

    try {
      throw new Exception();
    catch(Exception e) {
        StringBuffer sbTrace;
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        sbTrace = sw.getBuffer();

        // sbTrace has the error message that includes
        // the file and line number

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now