sharptooth
sharptooth

Reputation: 170489

Can I make Java compiler emit a specific error message and stop compilation?

In C, C++ and C# there's #error directive which makes the compiler stop compilation and emit a specified error message.

#error "Ouch!"

causes VC++9 to emit the following:

1>Source.cpp(10) : fatal error C1189: #error :  "Ouch!"

and stop compilation.

I can't find anything equivalent for Java.

Does Java have anything like #error directive that makes the compiler stop compilation and emit a specific error message?

Upvotes: 2

Views: 413

Answers (2)

Icarus3
Icarus3

Reputation: 2350

If you are desperate you could use "javax annotation processing APIs" to achieve something similar. see this

The idea is to use:

javax.tools.Diagnostic.Kind.WARNING

or

javax.tools.Diagnostic.Kind.ERROR

Upvotes: 1

gexicide
gexicide

Reputation: 40068

The question is, why would you need that in Java? In C/C++ you have #ifdef so you can emit an #error if a specific static condition is true. In Java, you have no such thing, all code is always compiled. Thus, you will always get the error. Having a file that always yields a compile error is not much use.

If you really need a file that always raises an error:

You can simply add a usual syntax error; you will not get a customizable error message but you will get a file that does not compile. You can add a comment behind the error. As most compilers display the line where an error is encountered, that comment will be displayed. Why not simply reuse #error:

In your java program:

#error // Description

Since # is not recognized by the Java compiler, this will yield a syntax error.

Upvotes: 4

Related Questions