Alexander Mills
Alexander Mills

Reputation: 100320

Print stack trace saying "Warning" instead of "Error"

I have this which represents a warning not an exception/error.

new Error("Warning: Callback fired more than once.").printStackTrace(System.err);

It looks this:

java.lang.Error: Warning: Callback fired more than once.

my question is, how can create a warning instead of error, something like this:

new Warning("Warning: Callback fired more than once.").printStackTrace(System.err);

so that it prints out:

java.lang.Warning: Warning: Callback fired more than once.

Upvotes: 0

Views: 1163

Answers (4)

DrHopfen
DrHopfen

Reputation: 847

You should facilitate a logging framework to do this. Depending on which you are using it would then look like logger.warn("Callback fired more then once."). If you need the stack trace as well you could add that to the log message. If there is no logging framework involved which might become unhandy at some point you can print the warning to standard out: System.out.println("Warning: Callback fired more than once.")

Upvotes: 4

GhostCat
GhostCat

Reputation: 140613

You can't.

so that it prints out:

java.lang.Warning:

The java.lang package is "sealed", you can't create your own classes that live in that package.

From that point of view, the best you can achieve is to create your own subclass of RuntimeException, to end up with

your.com.whatever.Warning: Warning

Beyond that, the other answers are correct: this is a solved problem. You are about to re-invent the wheel, so the real answer is to step back, and research logging frameworks, and to use one. And also research how to use Java exceptions in the first place, it is plain wrong for your code to throw instances of Error! Errors are really terrible things that get thrown by the JVM itself, for severe error conditions. They should not be used for bugs in your code, or whatever kind of assert you are thinking about here.

Upvotes: 1

xingbin
xingbin

Reputation: 28289

You can not do this directly, a possible way is using a logger:

public static void main(String[] args) {
    java.util.logging.Logger logger = java.util.logging.Logger.getLogger("");
    logger.warning("warn message");
}

Upvotes: 1

dehasi
dehasi

Reputation: 2773

You can create your own exception type

public class Warning extends RuntimeException {
  //override constructors
}

Then you will be able to do things like

new Warning("Warning: Callback fired more than once.").printStackTrace(System.err);

Upvotes: 2

Related Questions