Calling a Java main function - java

I am trying to call another JAR's main function. Now, this main function is enclosed under a try and catch block.
But when the main call returns a "NullPointerException" the program just crashes instead of catching it.
So, for example
try {
somelibary.main()
}
catch (Exception e) {
System.out.println("Exception Caught");
}
This code dosent catch NullPointerException from the main().
Does anyone know the reason y?

Your code, as shown, will definitely catch a NullPointerException thrown by somelibrary.main(). If the application stops anyway due to a NullPointerException there's a fair chance that somelibrary at some point catches the exception, dumps a stack trace and calls system.exit()
In that case the question is not how to catch a NPE, but how to prevent System.exit() from actually exitting.
And the answer to that question can, of course, be found on StackOverflow to, right here. Just install a SecurityManager before the call to someLibrary, and reset the securityManager afterwards.

It's possible that the other main function is doing its own error handling, à la
public static void main(String[] args) {
try {
....
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
If that's what the other main function is doing, then you won't be able to catch its exceptions. Do you have the code for this main function?

With the code you are showing, you will catch also the NullPointerException. But the execution will go on after the catch-block. So the execution of somelibary.main() is stopped in this case. If your main() is not contain more code, the program will end after catching the exception. That's what likely happens. You could post the complete code of your main, to verify this.
Addition: You want to know how to go on with the execution of the program. But in this case somelibrary.main() is stopped by throwing the exception. The only option in the main-class will be a loop, that reexecutes somelibrary.main(). The other possibility is to catch the Exception at some higher level (main input-loop) where you can ignore the problem and go on with the execution of the code. As you say you execute another jars-main I suspect you cannot change the code of the other jar. So you are only left with reexecute the other main:
boolean ended = false;
while (!ended)
{
try {
somelibary.main()
ended = true;
}
catch (Exception e) {
System.out.println("Exception Caught");
}
}
This code restarts the other main on an exception but ends if the other main ends normally.

Perhaps you could execute the main method in another process using Runtime.exec, then capture the result or the error from out/err stream.

Related

Java - TestNG : Is It Wrong to use testng Assert.fail() in a catch block

I came across a code written by someone with Assert.fail("some text") in a catch block. This is my code:
try {
//WebDriver code here which interacts with WebElements
//When an exception occurs in this try block, it will be caught in
//the catch and further catch block has Assert.fail()
} catch (Exception e) {
Assert.fail("failed to click 'Webelement' ");
}
I somehow felt this is not right way to do it. Am i wrong?
Note: Not exactly a duplicate of Is Assert.Fail() considered bad practice , As i am not expecting any Exception. If any exception occurs i need to fail the test case
Though it's syntactically not incorrect. But you should preferably rephrase your tests to use expectedException instead and be specific about the exception is thrown as well. For e.g. :
If your method fromTest() when called with "test" as an argument could throw an NumberFormatException, then your test definition for such behaviour should be :
#Test(expectedExceptions = NumberFormatException.class)
public void testMethod() {
System.out.println("About to throw an exception!");
fromTest("test");
}
Note: If you believe that the exception may so happen within your test execution itself instead of any other method being called from it. I would suggest to not catch it. Let it fail and then you shall fix it.

How to go to catch block without throwing exception

I have a java class which is throwing IOException.I have some code in Catch block which i need to debug. I don't know in which case my java class is throwing exception. So I need to go to catch block explicitly without throwing. Can it be possible.
Please help me out.
Code in a catch block is not executed if no matching exception is thrown in the try block.
The only way to execute it is to cause the IOException to be thrown.
You can just put an explicit throw new IOException(); as the last line in the try block.
Alternatively, you might be able to pull the contents of the catch block into a separate method, which you can then invoke explicitly.
Control wont goto catch block if exception is not thrown. Put the code in finally block which you want to execute irrespective of whether exception thrown or not.
Sample:
try {
} catch() {
} finally {
//Put code here
}
but if the exception is thrown you will be directed towards finally block or you can post sample code so one might help you

Exception in try-catch-block is not caught in Java

I am quite new to Java and stumbled upon an problem, I can't understand (I am using Eclipse Luna for developing and executing):
I call a method that might throw an error and surrounded it with a try-catch-block:
try {
transaction.execute();
} catch (ModbusIOException e) {
log.debug("Fehler bei Modbustransaction: ModbusIOException - " + e.getMessage());
e.printStackTrace();
} ... // more catches
The execute-method actually throws the ModbusIOException - but it is not caught in the catch-block. In the console I got the following output:
net.wimpi.modbus.ModbusIOException: Read failed
at net.wimpi.modbus.io.ModbusTCPTransport.readResponse(ModbusTCPTransport.java:180)
at net.wimpi.modbus.io.ModbusTCPTransaction.execute(ModbusTCPTransaction.java:193)
at de.vksys.modbusclient.ModbusClient.getPlantState(ModbusClient.java:121)
at de.vksys.modbusclient.ReconnectingModbusClient.main(ReconnectingModbusClient.java:36)
If I click at the line with getPlantState Eclipse marks the line in the try-block above. But why isn't it caught there? I also checked the full name of the ModbusIOException in the catch block and is the same ... net.wimpi.modbus.ModbusIOException.
Any idea, what might be the reason? If you need more code to track this down, just tell me.
Thanks in advance,
Frank
It indeed caught the exception. You just printed the stack trace and that's what you see in the standard output.
Catching an exception, doesn't mean that it wont maintain the stack trace and handling exception means that you need to code it so you could recover from the exception (which is what has happened in your case else your program would have went to the parent method which called your method rolling back the stack i.e. in readResponse method) where you might say ok things happen or you rethrow the exception. for e.g. given a code as below:
void myMethod() {
try {
methodThatThrowsIOException();
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("I will be printed");
If you didn't caught the exception, then you would never have executed print statement like "I will be printed"
}

Is there a way for me to throw an exception without it printing the stack trace?

The goal is to be able to do:
throw new RuntimeException();
without it printing:
Exception in thread "main" java.util.RuntimeException
at grame.GrameManager.add(GrameManager.java:40)
at grame.GrameManager.add(GrameManager.java:47)
at grame.Entity.<init>(Entity.java:56)
at grame.Entity.<init>(Entity.java:28)
at test.Test.main(Test.java:20)
(for example).
Is this possible? If so, how would I go about doing this?
Since exceptions are important, you could use a logging mechanism like log4j (http://logging.apache.org/log4j/1.2/) and set the logging to a different level when you don't want some exceptions to be printed or log to a file instead of console for example.
If you just don't care about the exception, catch it and do nothing with it (empty catch, which is awful).
You can redirect System.err by setting System.setErr(null);
No thrown exception ever directly generates a stacktrace to the error console. It's up to the code who is calling it to do so. In the case of a main program:
public static void main(String args[]) throws Exception {
// do something that throws an exception
}
If you don't catch the exception, the system will actually spit it out to the console i believe.
Somewhere along the way, you need to deal with the exception. If showing it in the GUI is what you want, then you'll have to do something like this:
public interface ExceptionHandler {
void handleException(Exception e);
}
public static void main(String args[]) {
ExceptionHandler exceptionHandler = ...;
try {
// something that might throw an exception
}
catch (Exception e) {
exceptionHandler.handle(e);
}
}
Just catch the exception, and don't put anything in the catch block.
I should add that doing this is generally a bad idea. Having that stack trace, or some sort of message is very useful when finding out what went wrong in your program.
If you want the method to kill the program without printing a stack trace, place it in a try/catch block, and under catch simply use the statement:
System.exit(1)
This lets the system know that the program exited with an irregular (non-zero) state, but does not print anything to System.err.
All that you really need to do is catch it... However, this is a really bad idea. You may want to make your own exception and catch that. This way you will not swallow exceptions that you should not be ignoring. The only time that you should really consider to do this, is if you cannot allow your application to blow up. If that is the case then you should at the very least log the error.
This explains it better than I can (and is a good resource regardless). Basically, it suggests that:
"If a client can reasonably be expected to recover from an exception,
make it a
checked exception. If a client cannot do anything to recover from the exception,
make it an unchecked exception".
Like this:
try {
some code...
} catch (RuntimeException e) {
}
1. Java compiler only cares during compilation that you have given a catch for a try, whether you implement any code in the catch or not.
2. You can keep the catch block empty, or print it on the console, log it..etc....
eg:
try{
}catch(Exception ex){
}
3. But printStackTrace() prints the method name, class name , file name and the line number where the exception has occurred.

Unable to understand behaviour of Finally Block

I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.
class Main
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod() throws Exception
{
throw new Exception(); /* Line 22 */
}
}
You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.
If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.
There is nothing to cause the program to exit.
The whole point of a catch block is to catch the exception and prevent it from propagating further.
After catching an exception, execution continues.
The finally block doesn't finalize the program, it just ensure to execute every time the try catch block runs whereas there is an exception or not..
It would print BC if you re-throw the exception in catch block.
catch (Exception ex)
{
System.out.print("B");
throw ex;
}
Then you'll have to declare your main as
public static void main(String [] args) throws Exception
Finally is called at the end of a try/catch block. It gets called even if the try fails and the catch is executed. The Finallyblock itself is only not executed if the program is killed somehow (JVM dies, forced to close, etc.)
In your example D is executing because it is outside of the try/catch/finally{} blocks.
There is a nice blog post on catching exceptions and the try/catch/finally behaviour here.
Which is correct. The above code will.
Try to execute badMethod and will fail
Execute the code in catch
Execute the code in finally
Continue in execution - print out the D
The finally block is processed after the try or catch block runs (depending on whether an exception was thrown/caught or not). If the exceptions were all caught properly and handles by the catch, it will run finally and then continue running the rest of the method.
Finally is the must executable block of java program.
It allows all the allocated resources of the currently running program to get free and make it available for the other applications if required.
This is mainly used when we share the common resources like Database or the devices.
Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.
And so in your case, badMethod throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.
In other words, if badMethod decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.
Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.
try
{
fooA();
}
finally
{
fooB();
}
Your program is functioning in the following way:
1. Call a bad method that throws an exception
2. Catch the exception
3. Execute the finally block
4. Resume
In Java, when an exception gets thrown it does not necessarily end program execution if the exception is handled. Your program does not actually handle the exception but catches it anyway and this is enough for the JVM to think it's ok to resume execution.
The output BCD is quite the right output.

Categories