views:

189

answers:

2

Im am currently developing an automated "test" class (running several individual tests on other classes in the same package). The aim of the test file is to show whether each test either passed or failed. Some of the files being tested are not written correctly creating an ArrayOutOfBoundsException when running the test, that produces my test file to crash and not carry on until the end performing other tests. I am not in the position to modify code to fix the errors on the project being tested.

-> how to stop an exception from halting program execution in Java without creating any new classes

Thank for all your help, advice and sharing.

+4  A: 

Best way to stop it happening: fix the code to perform appropriate checking.

If you can't fix the code which is actually failing, you could catch the exception explicitly at an "outer" level, log a warning and continue with the next file:

try
{
    operationWhichMightThrow();
}
catch (ArrayIndexOutOfBoundsException e)
{
    log.warning("Failed file " + filename, e);
    // Do whatever you need to continue to the next file.
}
Jon Skeet
Ok thanks a lot Jon, i will use the if-catch, as am not allowed to modify the code given am "evaluating" others work. All the best.
Carlucho
So, you can modify the code in the tests?
Scobal
@Jon Skeet, actually after trying to figure out how to use the try-catch block is not gonna workout very well in this case. I would not want to create any extra classes, is it possible to catch a method in the same class "testfile"?
Carlucho
@Scobal yes I can do anything I want with the 'testfile' class as I am the one to develop it. What am not in the position to do is to modify the methods and classes of the projects am testing
Carlucho
@venezuelan_pimp: It's not very clear what you're asking, but I suspect so. But if the exception is actually occurring in your class to start with, then you can avoid it by just making sure that you use appropriate array indexes to start with.
Jon Skeet
@Jon Skeet: Sorry for being unclear when formulating my question I sometimes find difficult to write down my thoughts in English. Regarding the exception, it is not occurring in the same class, is occurring in another class in the same package. I am not allowed to modify/fix the code throwing the exception in the class being tested (other). Your solution was excellent i just shaped it by catching "ArrayIndexOutOfBoundsException" instead of "ArrayOutOfBoundsException" that way i didn't have to create an extra class for it in the package. Thanks for all your help Jon you are really kind.
Carlucho
@venezuelan_pimp: Ah, sorry for getting the exception type wrong - I didn't have time to check it, so I just copied it from the title of your post :)
Jon Skeet
@Jon Skeet: Hehehe, thats OK. You just had me 1hr scratching my head thinking... But what does he mean!!??... Just kidding!Thanks again Jon.
Carlucho
+1  A: 

Catch the exception and log it as a test failure.

EJP