I have a unit test case, which involves creating some files with random contents, then test using the files and as clean up, delete the files.
So I need to create files and write to files in @Before method. How should I handle exceptions?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your test class needs those files to perform its tests, then you should declare the @Before method with
throws IOException. That way, if the creation of the files fails, the test class will fail and the reason will be obvious from the exception. If you catch and suppress the IOException, the unit tests which need those files will likely fail anyway, and it will be in a way that will require detective work.For the @After method, the stakes aren’t as high. I would declare the @After method with
throws IOExceptionjust because it’s easier to code and to read. You could probably catch the IOException without doing much harm, but then, shouldn’t the cleanup always succeed? If that code can’t clean up the files, something is weird about your environment and it’s probably good to be aware of it. So that’s another reason to addthrows IOExceptionto the @After method.