I have a java project which does not output the same result every time it is ran and object variables are changed upon each call of the starting method in main, resulting in a case where an errors are not thrown for some runs of the program, but sometimes an error may pop up in a niche case. This has led me to running the program over and over until some exception may be thrown.
Is there a way in Eclipse to run main over and over x amount of times until it encounters (or doesnt!) a caught error?
You can use the try catch keywords.
public static void main(String[] args) {
try {
// do something
}
// exits system if encounters any exception
catch (Exception e) {
System.exit(0);
}
}
If you wish to run the main method a specific number of times, you can put all your method inside the try statement and then inside a for loop. If you are looking for a specific exception, you can change the word "Exception" to your desired exception. For example:
try {
// do something
}
// exits system if encounters any exception
catch (ArrayIndexOutOfBoundsException e) {
System.exit(0);
}
You can put as many catch statements as you would like for each of the desired exceptions
Related
I have many hours struggling with this problem.
I have the following line of code:
Mockito.doReturn(new ErrorResponse()).when(mockobjectMapper).readValue("Test", ErrorResponse.class);
The method "readValue" spits an error:
Unhandled exceptions: com.fasterxml.jackson.core.JsonProcessingException, com.fasterxml.jackson.databind.JsonMappingException
I can surround it with try-catch block, but I have many different classes which will have the same catch. For example:
try {
Mockito.doReturn(someObject1).when(someMock).execute(Mockito.eq(someObject2));
} catch (SomeInterfaceException e) {
// Will never be reached
log.error("{}", StructuredArguments.fields(e));
}
How can I move the try-catch block to an utils class with a method which will receive the line of code which spits the error?
I know questions like this are everywhere, but I read a lot of things about this, and I still can't understand what the "throws" command do. I will be more specific now:
So, one of the examples I saw was this one, with the following code:
public class CatchThrow {
private static void throwsMethod() throws NumberFormatException {
String intNumber = "5A";
Integer.parseInt(intNumber);
}
private static void catchMethod() {
try {
throwsMethod();
} catch (NumberFormatException e) {
System.out.println("Convertion Error");
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
catchMethod();
}
}
Now, if I remove the "throws NumberFormatException" from the "throwsMethod" method, the program will run the same, and will give the same results. Actually, every example with the throws command that I saw did the same, so I can't really understand why use it.
I'm using the Eclipse IDE, version 4.7.2.
Normally your function exits at the end of the function or the return statement.
However, a function can also exit when it reaches a throw statement. If the exception subclasses Exception, the caller of the function must surround the function call with a try { } catch { } block. If the exception subclasses RuntimeException you may optionally surround the function call in a try catch block.
If you look at the JavaDoc for NumberFormatException: https://docs.oracle.com/javase/7/docs/api/java/lang/NumberFormatException.html will see it subclasses RuntimeException. This means your try-catch block is optional. The difference between the two program is this: With the try-catch block you will get Convertion Error printed to the console, without it, you will see the full stack trace. This is often called "swallowing the exception".
So basically, if an exception occurs and you don't want to handle that exception there, in that case you use the 'throw' keyword to simply just throw the exception if occurs.
Example: Here, in throwsMethod(), you are not taking care of the Exception Handling i.e. not using the try(), catch() blocks, you are just throwing it if there occurs any Exception. And you will land in catch() block if exception occurs in your throwsMethod().
To get better idea, you should read checked & Unckecked exceptions in Java. For Checked exceptions (happen at compile-time), we use 'throw' keyword and for Unchecked (Run-time), we use try() catch().
Example: NumberFormatException is an Unchecked exception, IOException is a Checked exception.
Read this for reference: https://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/
In my eclipse plugin I use a ScheduledExecutorService for a repeating task. However this seems to lead to some unreachable code within the scheduled task because I can set a breakpoint in eclipse up to a certain line and it will be reached in the debugger but when I set it one line further it is not reached... Just nothing happens then, no exception just nothing.
When I try to overstep this respective line I land somewhere in the sources of the ScheduledThreadPoolExecutor and my stack shows this:
ScheduledThreadPoolExecutor$ScheduledFutureTask<V>(FutureTask<V>).run() line: not available [local variables unavailable]
Whats going on here?
Okay the problem was that there was actually an exception being thrown but it seems like the ScheduledExecutorService swallows it without telling anything about it...
I foud this out by surrounding my code in the run-method with a generic try-catch-block like this:
#Override
public void run() {
try {
// Code
} catch (Exception e) {
e.printStackTrace();
}
}
Is there a way to find out which line in a try block is throwing an exception?
I'm working on Java in Eclipse which looks like
try {
//Lots of code. Seriously. Lots.
} catch (Exception e){
throw new OtherException();
}
I'm hitting an exception in the try block, (which is then caught). How do I figure out where it's being thrown from?
Problems
The stack trace only shows the line in the catch block for the OtherException
Removing the try/catch block isn't straightforward, as there are many exceptions declared as thrown which are required to be caught in order for the code to compile.
It feels like there should be a straightforward way of doing this.
Note: I didn't write this code ;-)
Use the cause parameter for Exceptions (see here):
try {
//Lots of code. Seriously. Lots.
} catch (Exception e){
throw new OtherException(e); // Trick is here
}
This way you get the cause exception as well in the stacktrace.
You can use throw new OtherException(e);. As the documentation explains, this constructor constructs a new exception with the specified cause.
In Eclipse, you can set a breakpoint triggered by an exception. See Add Java Exception Breakpoint.
For this particular case, you'll need to ensure that "Suspend on caught exceptions" is ticked.
Once Eclipse breaks into the debugger, you'll have a lot of tools at your disposal. You'll see the call stack, will be able to examine variables etc.
Just print stacktrace or run on debug mode
e.printStackTrace()
Pass the exception e in your OtherException constructor when throwing it. It will give you the complete stack trace with the exact line throwing the exception:
catch (Exception e) {
throw new OtherException(e);
}
If OtherException doesn't have a constructor that takes an Exception or Throwable you could do:
catch (Exception e) {
OtherException o = new OtherException();
o.initCause(e);
throw o;
}
You can also try printing out the error message to the console: System.out.println(e.getMessage());
Breakpoints are very useful though, since you can then trace through the code and see exactly when it gets to the catch block.
public class StackTest {
public static void main(String[] args) {
show();
System.out.print("welcome back to maain");
display();
}
static void show(){
try{
show(); //recursion
}catch(StackOverflowError e){
System.out.print("error cought");
}
}
static void display(){
System.out.print("after stack overflow error");
}
}
In this program an StackOverflowError occurs but gets handled and the program does not terminated abnormally. why?
You can see this at http://ideone.com/vwSav
You can handle Errors because they are Throwable just like Exceptions.
Errors are designed to indicate problems outside your program's control, like OutOfMemoryError and StackOverflowError, but you can define your own errors, too.
Perhaps you are thinking that, or heard that, OutOFMemoryError can be caught but there's no guarantee you'll have enough space to execute the handler, so errors must in general not be something you can catch. In your case, though, you got away with it. No language rules were violated in the catching and handling of this error.
The real question is, should you catch them? Normally when an error, as opposed to an exception, is thrown, your application is very likely in an inconsistent state, making recovery a crapshoot at best. So be really, really careful. Better to forget it and let the app die though, since whatever is running after the handler is not guaranteed to be something you'd want to run.
Why would you expect it to terminate when you catch the exception (or rather the Error in this case)? What else would that catch block do?
You can catch and handle pretty much all error conditions, though usually you should only catch Exceptions.
You can catch any Throwable and it is up to the developer to handle it correctly. You can even handle ThreadDeath (triggered by a Thread.stop()) or another sub-class of Throwable (which is neither an Error or an Exception)
public class MyThrowable extends Throwable { } // checked "exception"
try {
throw new MyThrowable();
} catch (Throwable t) {
t.printStackTrace();
Thread.currentThread().stop(t); // rethrow blindly.
}
It will only be terminated abnormally if your exception is propagated all the way up to your main method and you don't handle it there. Usually happens for unchecked run time exceptions. If you want to terminate your program and shut down the VM you can call System.exit(int errorCode) in the catch block, there will be programmers which always complain here if that's done but that's a way to do it.
usually you don't catch Error, except for LinkageErrors, no class def found errors, unsatisfied link errors, incompatible class change errors..
also an outofmemory error (sometimes the stackoverflow exception) doesnot give control the catch block as there is no memory.