Catch assert false using reflection - java

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.

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);
}

Catch the same exception twice

I have the following:
public void method(){
try {
methodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException e) {
anotherMethodThrowingIllegalArgumentException();
return;
} catch (IllegalArgumentException eee){ //1
//do some
return;
} catch (SomeAnotherException ee) {
return;
}
}
Java does not allow us to catch the exception twice, so we got compile-rime error at //1. But I need to do exactly what I try to do:
try the methodThrowingIllegalArgumentException() method first and if it fails with IAE, try anotherMethodThrowingIllegalArgumentException();, if it fails with IAE too, do some and return. If it fails with SomeAnotherException just return.
How can I do that?
If the anotherMethodThrowingIllegalArgumentException() call inside the catch block may throw an exception it should be caught there, not as part of the "top level" try statement:
public void method(){
try{
methodThrowingIllegalArgumentException();
return;
catch (IllegalArgumentException e) {
try {
anotherMethodThrowingIllegalArgumentException();
return;
} catch(IllegalArgumentException eee){
//do some
return;
}
} catch (SomeAnotherException ee){
return;
}
}

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 Catch Object Error

This code below is the method header and body, but I get the following error: no exception of type object can be thrown an exception type must be a subclass of Throwable. I'm attempting to execute this block of code: catch(Object object).
public void method15665(Class435 class435, int i) {
do {
try {
try {
byte[] is
= new byte[(int) class435.method7563(1085678935)];
int i_3_;
for (int i_4_ = 0; i_4_ < is.length; i_4_ += i_3_) {
i_3_ = class435.method7564(is, i_4_, is.length - i_4_,
(byte) -10);
if (i_3_ == -1)
throw new EOFException();
}
Class224_Sub8 class224_sub8 = new Class224_Sub8(is);
if ((class224_sub8.aByteArray8535.length
- class224_sub8.anInt8536 * 475822179)
< 1) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
int i_5_ = class224_sub8.method13859((short) -7287);
if (i_5_ < 0 || i_5_ > 1) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
if ((class224_sub8.aByteArray8535.length
- class224_sub8.anInt8536 * 475822179)
< 2) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
int i_6_ = class224_sub8.method13737(2071056893);
if ((class224_sub8.aByteArray8535.length
- 475822179 * class224_sub8.anInt8536)
< 6 * i_6_) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
break;
}
for (int i_7_ = 0; i_7_ < i_6_; i_7_++) {
Class323 class323
= Class399.aClass195_Sub2_Sub1_5932
.method14614(class224_sub8, -2141543778);
if ((Class255.aClass255_3016
== (((Class173_Sub1) this).aClass255Array9960
[class323.anInt5015 * 1568411443]))
&& (Class399.aClass195_Sub2_Sub1_5932.method14624
(class323.anInt5015 * 1568411443, 82620551)
.aClass350_2171.method6687
(-1035085164).aClass5162.isAssignableFrom
(class323.anObject5014.getClass())))
anInterface50_2149.method298((class323.anInt5015
* 1568411443),
class323.anObject5014,
-1250481088);
}
} catch (Exception exception) {
try {
class435.method7572(-1683167102);
} catch (Exception exception_8_) {
exception = exception_8_;
}
break;
}
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
} catch (Object object) {
try {
class435.method7572(-1683167102);
} catch (Exception exception) {
/* empty */
}
throw object;
}
} while (false);
}
Does anyone know how fix this? It would be very much appreciated!
replace
} catch (Object object) {
with
} catch (Throwable object) {
actually you don't want to catch Throwable, but probably Exception, RuntimeException or an even more specific class.
You can only catch what can be thrown (IS-A Throwable). Hence, the compiler complains when you try to catch an Object (because it doesn't extend Throwable).
catch (Object o) // Error: Object IS-NOT Throwable
Throwable is inherited by all types of Errors and Exceptions. But, we usually don't catch Errors because a program almost always cannot recover from it for example, an OutOfMemoryError. So, a catch (Throwable t) is not recommended.
When using catch (Exception e) you basically have a catch-all for any exception (checked or un-checked) that might get thrown during the run. To use or not to use a generic catch usually depends on what you're try block is trying to do. For example, when reading a file you would like to handle and respond to a FileNotFoundException differently than say an EOFException.
All exceptions and errors extend Throwable, only those can be thrown and caught.
You can do
try{
throw new Exception();
}catch(Exception e){
// something here
}catch(Throwable t){
// something here
}
When you are writing multiple catch blocks, then keep following points in mind
You cannot write a subclass type AFTER a superclass type. i.e. If you write catch(RuntimeException rt){} AFTER catch(Exception e){} then you will get compiler error that it is already caught.

assertTrue/assertFalse if statements

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.

Categories

Resources