assertTrue/assertFalse if statements - java

How can you use assertTrue and assertFalse in if statements? Just throwing in if statement in front does not work, gives me a syntax error, but it was worth a shot. I tried to make it a string and check value with value.equals() but assert gives an error saying you cannot convert to a string.
public class JNAWinRegTest extends TestCase {
public static void main(String[] args) {
try { assertEquals("Windows 7 Professional", Advapi32Util.registryGetStringValue(WinReg.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName"));
if(True) ){
System.out.println("True");
}else{
if(False) ){
System.out.println("False");
}
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}

You just call assertEquals(expected, actual) - if expected.equals(actual), the test continues to the next line (and pass when it reaches the last line), if the condition is false, the test fails.
No need for additional if / else.

Related

IF inside try block

I want to execute my method callmethod if the condition inside the IF statement is met. Else it should execute the catch block. But during implementation, if the condition is not met, it does not go to the catch block.
try{
if(count==0)
callmethod();
}
catch (Exception e){
System.out.println(e);
}
This is a good application for methods:
try {
if (count == 0) {
callOneMethod();
}
else {
callOtherMethod();
}
catch (Exception e) {
callOtherMethod();
}
That way you don't have any duplicated code and you're not doing weird things with exceptions in non-exceptional cases.
Since you are trying to hit the catch block, you need to throw an exception if your parameter is not met (i.e. count != 0).
Example:
try {
if(count==0){
callmethod();
} else {
throw new SomeException("some message");
}
}
catch (Exception e){
System.out.println(e);
}

In java I want to jump from a particular block of Statements to another block of statements. How can I achieve it?

public class abc{
public static void main(){
try{
int a =10;
if(a=10){
throw new Exception();
}
l1:System.out.println(a);
}catch(Exception e){
continue l1;
}
}
}
Actually what I am trying to do is when an exception occurs I wish to continue the next statement after that as well.
Is there any way I can achieve it with Java?
You would just want to put System.out.println(a); in the catch block.
Putting it in a finally block would mean that it is executed even when an exception does not occur. The program only goes to the catch block when an exception occurs.
I think this is what you want?
public static void main(String[] args) {
int a = 9;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
Or if a is 10
public static void main(String[] args) {
int a = 10;
try {
if (a == 10) {
throw new Exception();
}
} catch (Exception e) {
e.printStackTrace(); // only if there is any exception
} finally {
System.out.println(a); // always print this message
}
}
try some thing like
int a =0;
try{
a =10;
if(a=10){
throw new Exception();
}
} catch(Exception ex){
//do nothing
} finally {
l1:System.out.println(a);
}
Anyway in java avoid jumping

Android / Java: how to define a code block and leave it without custom exceptions?

I seem to be stuck with a very simple task that would require GOTO statements and, in my opinion, would justify a use of those.
I have the very simple task to exit a void on different conditions. Within its code, several dozen operations are being done and most of them can fail. I test them with try {}.
Now, based on the criticality of the operation, I either need to exit immediately and do nothing else, or, I just need to interrupt control flow and jump to a final point to do some cleaning up and then exit the method.
MWE:
public void myMethod () {
try { op1(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op2(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op3(); } catch (Exception e) { return; } // Fail here: exit immediately
try { op4(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
try { op5(); } catch (Exception e) { cleanUpFirst(); return; } // Fail here: do Cleaning up first, then exit
// ....
}
public void cleanUpFirst() { /* do something to clean up */ }
For code readability, I'd like to a) avoid a separate function and b) do not have more than one statement within the catch block; it just blows up the code. So, in my opinion this would perfectly justify the use of a GOTO statement.
However, the only solution I came up with, given that only two outcomes are possible, is this:
public void myMethod () {
do {
try { op1(); } catch (Exception e) { return; }
try { op2(); } catch (Exception e) { break; }
try { op3(); } catch (Exception e) { return; }
try { op4(); } catch (Exception e) { break; }
try { op5(); } catch (Exception e) { break; }
// ....
} while (1==0);
/* do domething to clean up */
}
Yes, I have heard of exceptions and that is is the Java way. Is that not as overkilled as using the separate void? I do not need the specifics, I simply need a yes/no result from each operation. Is there a better way?
why not
boolean cleanupfirst = false;
try {
op1 ();
cleanupfirst = true;
op2 ();
cleanupfirst = false;
op3 ();
} catch (Exception e) {
if (cleanupfirst)
cleanup ();
return;
}
You're over-thinking it.
4 minor adjustments.
Let Opn() return a boolean for success or failure, rather than throwing an Excpetion.
Let CleanupFirst handle program termination (you can rename it to clean exit if you want). The new parameter passed to CleanExit is the System.exit code.
Use System.Exit to return a proper return code to the OS, so you can use it in scripting.
It does not seem like your program has a successful path.
if (!op1())
System.exit(1); // <- send a failed returncode to the OS.
if(!op2())
cleanExit(2);
if (!op3())
System.exit(3); // <- send a failed returncode to the OS.
if (!op4())
cleanExit(4);
if (!op5())
cleanExit(5);
cleanExit(0);
More methods for better readability:
public void myMethod() {
try {
tryOp1();
tryOp2();
...
} catch(Exception ignore) {}
}
public void tryOp1() throws Exception {
op1();
}
public void tryOp2() throws Exception {
try {
op1();
} catch (Exception e) {
cleanUp();
throw e;
}
}

Java Do X IF catch was not called from a try loop

Not sure if this has already been answered, but.
I know that in java there is the try, catch and finally blocks, but is there one which is only called if try has no errors/exceptions?
Currently after stating the command that needs to be run, I'm setting a boolean to true, and after the try and catch block, the program checks for if the boolean is true.
I'm pretty sure that there is a much simpler way, help is appreciated!
Just put your code after the try...catch block and return in the catch:
boolean example() {
try {
//dostuff
} catch (Exception ex) {
return false;
}
return true;
}
This would also work if you put the return true at the end of the try block as the code would jump to the catch on error and not execute the rest of the try.
void example() {
try {
//do some stuff that may throw an exception
//do stuff that should only be done if no exception is thrown
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
No, there is no block called only if no exceptions were raised.
The catch block is called if there were exceptions, finally is called regardless.
As stated, you can emulate such a beast with something like:
bool completed = false;
try {
doSomeStuff();
completed = true;
} catch (Exception ex) {
handleException();
} finally {
regularFinallyHandling();
if (completed) {
thisIsTheThingYouWant();
}
}
but there's nothing built into the language itself that provides this functionality.

Catch assert false using reflection

The code in the file to test is:
public void testFail() {
assert false;
}
I need to catch this using reflection and increment a "failed" counter. This is my attempt:
try {
Object t = c.newInstance();
m[i].invoke(t, new Object[0]); // m is the array that holds all Methods for c
passed ++;
} catch (AssertionError ae) {
failed ++;
} catch (Exception e) {
errors ++;
}
}
The assertFalse just goes through as passed and does not raise any exceptions. How can I catch this?
Thanks.

Categories

Resources