Using the try catch statement to print out statements - java

#Test
public void test() throws Exception
{
try
{
//some code over here
}
catch(Exception e)
{
if(e.toString() == null)
{
System.out.print("Test Case: Successful");
}
else
{
System.out.println("Test Case: Failed");
System.out.println("Failing Reason: "+ e.toString());
}
}
}
Currently I have the above code.
However, when executing the JUnit.
Nothing was printed into the console.
Did I do anything wrong? Or is it that i cannot use System.out.println in JUnit.
So I have a second question:
Is it possible to print out the total amount of time taken to complete the JUnit test?

This code doesn't make sense.
If no exception is thrown, no exception is thrown, so you won't end up in the catch block; so there isn't a way you'd end up there in the "successful" case (unless you're testing explicitly for throwing an exception whose getMessage() returns null, which is... hmm; and in that case you should have a fail() as the last line of the try)
JUnit already handles failures for you. If your approach were the "right" way to do it, you'd have to put this code in every test case. What a lot of repeated code.
If the code in the try block fails by throwing an Exception, you catch and swallow the problem. Sure, it gets printed to the console, but JUnit has no means of capturing that, so it looks like the test passes. (It will still fail properly if an Error or other Throwable is thrown).
In short: just get rid of your try/catch block, leaving the code in the try, and let the testing framework do exactly what it is designed for.

Code in the catch block will only run if the code in the try block throws an exception. As you have it coded, it is not going to print anything out unless an exception is throw. This is likely what you meant:
#Test
public void test() throws Exception
{
try
{
//some code over here
// last line of try block
System.out.print("Test Case: Successful");
}
catch(Exception e)
{
System.out.println("Test Case: Failed");
System.out.println("Failing Reason: "+ e.toString());
}
}

Related

try catch exception handling scenario

I am looking to handle a multi-level error handling scenario, where I have a test looks somehwat like this:
void tester() {
String fileName = Path.of(myDir, "file_1.lo").toString();
assertThrows(
Error.class,
() -> TheCompilerClass.parent_method_called_by_testcase(fileName),
"Expected parse error to be thrown for this test"
);
assertTrue(getStdErr().contains("Failed to compile"));
}
And this invokes the code I have developed where upon exception I am trying to send back something that will result in bool: True at the assertTrue statement above.
My code structure is like this:
parent_method_called_by_testcase() {
try {
} catch (Exception e) {
System.err.println("Failed to compile ");
//how do I return the right thing?
//STDERR statements can't be returned back to test case invoking methoid?
}
}
child_method {
//this finds that exception has occurred and should pass it up the chain
//should this have a throw statement? or just a return?
if (exception) {
tell the parent so that parent can tell the testcase
}
}
Arguably, log lines like the one you mention are not part of what is generally tested in unit tests. More commonly, we test end functionality. For example, if the child method encounters a case where we throw an exception, does the parent method catch that? In other words, does the parent method throw an exception as well? This is an example of an assertion that one might write in a unit test.
Here, based on your test, your, assertThrows means that you expect the parent method to throw an exception here. So in your catch block, you would do some logging but ultimately throw e if you want the parent to throw if the child does.
parent_method_called_by_testcase() {
try {
...
} catch (Exception e) {
System.err.println("Failed to compile ");
throw e;
}
}

Can someone help me understand the working of try-catch block in java?

This might be a really dumb question to most of you here, really sorry about that. I am new to java and the book i am reading didn't explain the working of an example in it.
public class CrazyWithZeros
{
public static void main(String[] args)
{
try
{
int answer = divideTheseNumbers(5, 0);
}
catch (Exception e)
{
System.out.println("Tried twice, "
+ "still didn't work!");
}
}
public static int divideTheseNumbers(int a, int b) throws Exception
{
int c;
try
{
c = a / b;
System.out.println("It worked!");
}
catch (Exception e)
{
System.out.println("Didn't work the first time.");
c = a / b;
System.out.println("It worked the second time!");
}
finally
{
System.out.println("Better clean up my mess.");
}
System.out.println("It worked after all.");
return c;
}
}
I can't figure out where the control will go after another exception is generated in catch block in divideTheseNumbers() method ?
Any help will be appreciated !
Output for your program will be
Didn't work the first time.
Better clean up my mess.
Tried twice, still didn't work!
Didn't work the first time. - because of the catch block in divideTheseNumbers
Better clean up my mess. - because of the finally block in divideTheseNumbers
Tried twice, still didn't work! - because of the catch block in the main method.
In general when a exception is thrown from a method and if is not in a try block, it will be thrown to it's calling method.
There are two points to note :
1) Any exception that is not in a try block will be just thrown to
it's calling method(even if it is in a catch block)
2) finally block is always executed.
In your case, you are getting the second exception in catch block, so it will be thrown. But before exiting any method it will also execute finally block(finally block is always executed). That is why Better clean up my mess is also printed.
Some points regarding exception handling:
1. Place your code that may causes exception inside the try{} block.
2. Catch the appropriate exception using the catch block.
3. While catching exception it's better use more specific type exception instead of catching the generic exception like. For example you catch the Exception, in this case you may catch the more specific type exception ArithmeticException.
4. finally block always executed, even though you use return statement in catch or try block.
5. A method either throws or catch an exception. If a method catch an exception then for it is not required to throws the exception.
6. All exception need not to be handled by using catch-block. We can avoid the try-catch block for the unchecked exception like - ArithmeticException,NullPointerException, ArrayIndexOutOfBoundsException. See here for more.
You may also check the tutorial for learning more about exception handling.

Catch block is not getting executed

pls find the code below:
public static void selectDefinition(String defName)
{
driver.findElement(By.xpath("//table[#id='MainContent_gdvDefs_DXMainTable']//td[text()='"+defName+"']")).click();
}
and
try{
selectDefinition(defdelname);
System.out.println("Definition "+defdelname+" was not removed from the table");
}
catch (Exception ex)
{
System.out.println("Definition "+defdelname+"was removed successfully from the table");
}
in the above code if the "defdelname" is deleted the catch block is not executing but for selectDefinition it is throwing no such element exception.
i am a beginner pls help me out...to solve this issue i want the catch block to be executed any workaround for that?
You have to add throws Exception to your method, in this way the exception is thrown to the calle inside the try/catch block and correctly handled:
public static void selectDefinition(String defName) throws Exception
{
driver.findElement(By.xpath("//table[#id='MainContent_gdvDefs_DXMainTable']//td[text()='"+defName+"']")).click();
}
This is NOT how exceptions are meant to work. They are used to alert that an error has occured during the execution of your program and not to manage your program workflow. Also in your code you are using the catch block to report a successful status, the opposite of what an exception catch is for.
If your method can de both succesfull and not (it is a possible outcome to remove and to not being capable of remove from the table, according to your example) you should use a return statement with a meaningful value, such as a boolean true \ false variable. Exception should occur only if the behavior that created it was NOT meant to occur.

Resume code in try block after exception is caught

I am fairly new to using try/catch blocks, so I don't know how exactly to perform this command.
If I catch an error, I would like to wait a period of time(10 seconds or so) then try to run the same line of code to attempt to continue in my try block. My program is written in Java. I have looked at both these pages: Page1, Page2, but neither of them are in Java. I have also looked at this, but they are not solving in the using the catch block. Is this possible to do, and how would I implement this in my catch block instead of just printing the error?
99% of time, you want to re-run a code-block after a try-catch and not the line with exception.
If you need to run from that line, than that is an indication for you to take your code in another method that encapsulates only that code (maybe move the try-catch there too).
What i would advice is something like this:
void method(){
try{
codeline1;
codeline2;
codeline3;
codeline4;
}
catch(Exception ex)
{
restorClassStateBeforeCodeLine1();
method();
}
}
By that snipped i propose to have your entire try-catch in a separate method.
Waiting random intervals is bad practice also. You never know if 10 seconds is right every time or at all.
Another way that I advise against would be:
label: {
try {
...
if (condition)
break label;
...
} catch (Exception e) {
...
}
}
It uses java labels to retry that part. I never tried but the break could be moved in the catch and the label in the try.
I don't think it is possible to return to a certain line in your try-block from inside a catch-block. Because when the throwis executed, the runtime system is going to pop frames from the call stack, looking for an exception handler to match the thrown exception and once the frame is popped from the stack, it's gone. More info about this can be found here
What you can do is call the method that caused the throw from within the catch-block. But that means it is going to execute your method from the beginning, so maybe you want to try to rearrange your code so that this does not cause any other problems. EDIT: The other answer demonstrates exactly what I mean.
This simple program loops through array values, testing each until it finds a value that doesn't generate an exception
public static void main(String[] args) {
int[] array=new int[]{0,0,0,0,5};
for(int i=0; i<array.length;i++) {
try {
System.out.println(10/array[i]);
break;
} catch(Exception e) {
try { Thread.sleep(1000); } catch(Exception ignore){}
}
}
}
while(true){
try{
//actions where some exception can be thrown
break;//executed when no exceptions appeared only
}
catch(YourException e){
Thread.sleep(10_000);
}
}
This cycle will be repeated while you instructions haven't executed. When code in try-block executed succesfully break helps you leave this cycle
Since you are saying that it is only 2 lines of code that you experience the intermittent error with, try something similar to this.
public static void main(String... args)
{
try
{
//Some Logic
//Error throwing logic in method
while(!doLogic())
{
Thread.sleep(1000);//Sleep here or in doLogic catch
}
//Continuing other logic!
}
catch(Exception e)
{
e.printStackTrace();
}
}
static Integer i = null;
public static boolean doLogic()
{
try
{
//Lines that throw error
System.out.println(i.toString());//NPE First run
}
catch (Exception e)
{
i = 1;
return false;
}
return true;
}

Behavior of nested finally in Exceptions

Today at work, I had to review a code snippet that looks similar to this mock example.
package test;
import java.io.IOException;
import org.apache.log4j.Logger;
public class ExceptionTester {
public static Logger logger = Logger.getLogger(ExceptionTester.class);
public void test() throws IOException {
new IOException();
}
public static void main(String[] args) {
ExceptionTester comparator = new ExceptionTester();
try {
try {
comparator.test();
} finally {
System.out.println("Finally 1");
}
} catch(IOException ex) {
logger.error("Exception happened" ex);
// also close opened resources
}
System.out.println("Exiting out of the program");
}
}
It's printing the following output.I expected an compile error since the inner try did not have a catch block.
Finally 1
Exiting out of the program
I do not understand why IOException is caught by the outer catch block. I would appreciate if anyone can explain this, especially by citing stack unwinding process
A finally block represents a task that has to be done under both normal and abnormal conditions.
Example: You take an interview candidate to lunch. While at lunch, you find out he's wanted by the police for murder. Exception! Lunch is over, the interview is a total loss, but... you still have to pay for lunch.
try {
meetForLunch(interviewCandidate);
}
finally {
lunchBill.pay();
}
Note that paying for lunch hasn't taken care of the exception, you've still got to do something about the murderer at your interview. It's just a loose end that has to be taken care of before processing with damage control.
Most finally blocks are used in that way: A file needs to be closed whether you successfully saved the data or not, a database connection needs to be closed whether the transaction was approved or not, etc.
And the exception continues outward on its merry way, looking for a matching catch block in an enclosing scope.
Note that finally blocks will always run unless the process ends while the try block is still executing.
I think the problem is that your function
public void test() throws IOException {
new IOException();
}
Doesn't actually throw an exception - it just creates a new IOException() object. Changing this to
public void test() throws IOException {
throw new IOException();
}
should fix this.
The code above does not require much of an explanation - not definitely involving call stacks!. What is your confusion?did I miss something?
Here is my explanation
First point
You don't need both a catch and a
finally block. You can have one of
them or both of them with a
try-block, but not none of them.
The code inside the finally clause
will always be executed, even if an
exception is thrown from within the
try or catch block. If your code has
a return statement inside the try or
catch block, the code inside the
finally-block will get executed
before returning from the method.
So in the above code, an exception was never thrown (because you are not using throw in the test() method)
However, finally block got executed as promised by the the language spec and you got the output Finally 1. The next statement in the sequence of execution is the System.out.println("Exiting out of the program"); as the catch block never reached as there are no IOExceptions. So, Exiting out of the program is printed.

Categories

Resources