Java Approval Question

What exactly happens when a Java statement fails? How does a programmer know that the statement did not work?

Thanks.

+8
java
source share
7 answers

If statements are included in the JVM (using the -ea flag), then an AssertionError will be -ea if the statement fails.

This one should not be caught, because if the statement fails, it basically means one of your assumptions about how the program works. This way, you will usually find out about the assertion error when you get the completion of the exception stack trace with the end of your thread (and possibly the whole program).

+4
source share

An assertion will fail if you include assertions in the JVM when it starts. This can be done by specifying the -e option on the command line. If you do this, then this block of code will throw an AssertionError when it is executed:

 public void whatever() { assert false; } 

Statements should only be used to detect programming errors. If you are checking user input or something on these lines, do not use statements.

+4
source share

It throws an AssertionError , which is a subclass of Error . As a rule, like Error and as a failed statement, you probably shouldn't try to catch it, as it tells you about significant deviations in your code and that if you continue, you are likely to be in some undefined unsafe state.

+2
source share

If the statement fails and the statement is included at run time, it will throw an AssertionError .
Usually you use assert statements in JUnit tests, when you create an application, you use a test utility that checks for errors and tells you.

Take a look at this: Assertion Programming

+1
source share

It throws an AssertionError. However, you must compile the program with the -ea or -enableassertions flag to throw an actual exception.

+1
source share

It throws an Error . It looks like you are getting a NullPointerException , but it is a subclass of java.lang.Error . Name AssertionError .

It is like a NullPointerException in the sense that you do not need to declare throws or anything else, it just throws it.

 assert(false); 

looks like

 throw new AssertionError(); 

if you run your program using the -ea flag passed to the java program (VM).

0
source share

The programmer can write a catch try block, so if an error occurs, you can catch it in catch, and the programmer can find out

 try { assert false; } catch(Exception e) { System.out.println("Error has occured"); } 
0
source share

All Articles