I'm trying to debug a libgdx application... Obviously, I'm producing a NullPointerException at some point, but libgdx has a huge try-catch statement that catches my original exception:
public void run () {
graphics.setVSync(graphics.config.vSyncEnabled);
try {
LwjglApplication.this.mainLoop();
} catch (Throwable t) {
if (audio != null) audio.dispose();
if (t instanceof RuntimeException)
throw (RuntimeException)t;
else
throw new GdxRuntimeException(t);
}
}
So the debugger stops in the catch statement where the (Gdx)RuntimeException is thrown. I know that t contains the original exception, but I can't really tell where it came from. Is there any way to break at the line that produces that exception?
Untested with libgdx but in similar systems you might be able to do…
try {
foo.run ()
} catch (RuntimeException t) {
System.err.println ("** Caught a runtime exception.");
t.printStackTrace();
Throwable tCause = t;
while (tCause = tCause.getCause()) {
System.err.println("→ caused by:");
t.getCause.printStackTrace ();
}
}
It appears that GdxException.GdxException (Throwable) should call super (t) which in turn should “stash” t in the property for the getCause accessor.
PS: Have you tried running a static analyzer like FindBugs to locate potential NPE's?
How about inspecting the stacktrace and inserting a breakpoint where the NullPointerException is generated?
This is the solution that worked: Add the exception that is shown in t to the list of exceptions that should always trigger the debugger, even when being catched:
Break when exception is thrown
Thanks for the help though :)
Related
I'm new on Java, and I would like to know if Java has something like Python exception handling, where you don't have to specify the exception type. Something like:
try:
f = open('text.tx', 'r')
except:
#Note you don't have to specify the exception
print "There's an error here"
I hope you can help me.
Yes there is something called the try and catch block it looks something like this:
try
{
//Code that may throw an exception
}catch(Exception e)
{
//Code to be executed if the above exception is thrown
}
For your code above it could possibly be checked like this:
try
{
File f = new File("New.txt");
} catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
Hope this helps look at this for more information: https://docs.oracle.com/javase/tutorial/essential/exceptions/
Every exception in Java is some sort of extension of java.lang.Exception. So you can always do:
try {
// something that maybe fails
} catch (Exception e) {
// do something with the exception
}
It will catch any other type of exception, you just won't know what the actual exception is, without debugging.
You can't leave out the exception type, but the widest try-catch block would be:
try {
// Some code
} catch(Throwable t) {
t.printStackTrace();
}
which catches Exceptions, Errors and any other classes implementing Throwable that you might want to throw.
It would also be incredibly foolish to use that anywhere, especially in something as simple as file access. IOException is a checked exception, so whenever you're doing file operations you'll be reminded by the compiler to handle that exception. There's no need to do a catch-all, it only makes your code more brittle.
Code:-
try {
Assert.assertEquals("1", "2");
} catch (Exception e) {
System.out.println("I am in error block");
}
If the assert statements fails, I would like to capture the error in the catch block. I am trying with the above code and its not happening.
Will the assertion error be caught by in a catch block for java exception?
You have almost answered your own question. Your catch block will not catch the AssertionError that the Assert throws if it fails, because it is an Error (or, more specifically, it extends java.lang.Error). See the docs for more information on this. Your catch block only catches Throwable objects that extend java.lang.Exception
If you really want to catch it - you need to use
catch (AssertionError e) {
...
However, as others have mentioned, this is a very unusual way to use assertions - they should usually pass and if they fail it is very unusual for you to want to carry on the program execution. That's why the failure throws an Error rather than an Exception. You can read more about (not) catching Error in this question.
If you just want a test the variable value, it is preferred to use if ( variableName == "1")
NB if you are testing unit-test helper code, like a matcher, it might make sense to catch the AssertionError.
If you want to catch both Exception and Error instances use:
...
catch (Throwable t)
{
...
}
Since both Exception and Error extend Throwable.
Well, I believe you are using JUnit for writing your tests. In that case, you should not catch your Assert.assertEquals() because they should pass for normal test execution. If it throws any exception, it means that your code is not performing as it should.
If you want to catch the errors in that way you need something like the following:
if (num == 1 || num == 2) {
throw new Exception();
}
You could create your own exception class and pass in the message you want.
If you run following code then it will compile and run successfully,
public class Example {
public static void main(String[] args) {
// insert code here
try {
new Example().go();
// throw new OutOfMemoryError();
} catch (Error e) {
System.out.println(e);
}
}
void go() {
go();
}
}
With following output :
java.lang.StackOverflowError
So my question is "Can we catch an Error"..??
Answer to your question is yes, you can catch error in java. And your code is almost correct. Your method go() calls itself infinitely and therefore causes StackOverflowError that is caught in your catch block and printed by System.out.println()
Yes, you can catch an Error, but you are advised not to do it, since Errors indicate serious problems that a reasonable application should not try to catch. (as stated in the Javadoc of Error)
Yes, we can catch an error.
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the throw statement.
Similarly, only this class or one of its subclasses can be the argument type in a catch clause. For the purpose of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
try {
while(true) {
}
} catch (Throwable e) {
// TODO: handle exception
System.out.println(e);
}
Note that there's a difference between StackOverflowException and StackOverflowError, since you have an error, it's a serious indication that you should never try to catch it.
Just don't do infinite things in your code, when this error happens, no stack space is available, how would you want to proceed?
StackOverFlowError indicates that you have severe problems, it's a bad idea to catch this error, instead, try to understand what problems you have in your code and fix them.
Basically iterating through a list and,
- Invoke method on first object
- Catch the first exception (if any); if there are no more exceptions to catch, return normally. Otherwise, keep on invoking method until all exceptions are caught.
- Move on to next object.
I can iterate through each object, invoke the method, and catch one exception but I do not know how to continuously invoke the method on it and keep on catching exceptions.
This is similar to the other answers, but without the flag, which seems like clutter to me. I don't really understand the question though, so I'm just throwing it out there in case it is useful.
for (Item item : items) {
while (true) {
try {
item.doSomething();
break;
} catch (MyException ex) {
log.warn("Something failed.", ex);
}
}
}
This approach hinges on the operation of the unlabeled break statement, which completes abruptly and then exits the enclosing while statement normally.
Based on subsequent comments, I think there is some confusion about what it means when there are multiple exceptions declared to be thrown by a method.
Each invocation of a method can be terminated by just one exception being thrown. You can't somehow resume invocation where it left off, and handle subsequent exceptions.
So, if a method throws multiple exceptions, catch a common ancestor, and move on. For example, if a method throws java.io.EOFException or java.nio.channels.ClosedChannelException, you could simply catch java.io.IOException since it is a common ancestor. (You could also catch java.lang.Exception or java.lang.Throwable for the same reason.) Invoking the method again under the same conditions won't get you any further.
If you want to attempt to invoke the method on each object, even if some fail, use this:
for (Item item : items) {
try {
item.doSomething();
} catch (Exception ex) { /* This could be any common ancestor. */
log.warn("Something failed.", ex);
}
}
If you're talking about dealing with a single method call that will throw more than one exception, it can't be done -- no matter how many times you call the method, it will keep on throwing the first exception. You can't go back into the method and keep running from there; after throwing one exception, it's all over.
But if you're talking about a method that sometimes throws exceptions and sometimes doesn't, try something like this:
boolean thrown = false;
do {
try {
thrown = false;
method();
}
catch (Exception e) {
thrown = true;
// Handle as you like
}
} (while thrown);
This is what I understand.
You have an object's method which may throw a number of exceptions.
What you want to do is to catch them all and continue with the next object in the list.
Is that correct?
So, that would be:
for( YourObject o : yourList ) {
try {
o.thatMethod();//invoke that risky method
} catch( SomeExceptionClass sec ) {
// Do something with that exception
} catch( SomeOtherExceptionClass soec ) {
// Do something with that exception
} catch( YetAnotherxceptionClass yaec ) {
// Do something with that exception
} catch( OtherUnRelatedException oue ) {
// Do something with that exception
}
}
When you do this, if the invocation of thatMethod() throws an exception and that exception is listed in the catch section, the execution flow will jump to that exception and after it will continue to the normal flow ( which is the for loop and will continue with the next object )
I hope this is what to need. For more information read: The catch block in the Java Tutorial section Essential classes
I'm assuming that you are trying to performs some kind of validation to the items in a list, where the validation errors are reported by throwing exceptions. I'm also assuming that you are trying to collect all of the validation errors.
The simple answer is that this problem cannot be solved using this approach. To understand why, take a look at this:
boolean exceptionCaught = false;
do {
try {
item.doSomething();
} catch (MyException e) {
exceptionCaught = true;
}
} while (exceptionCaught);
This fails because each time you call item.doSomething() it is going to throw an exception at exactly the same place. The net result is an infinite loop.
The best you can do with this approach is to capture the first exception for each item in the list.
So how can you achieve what you are trying to achieve? The answer is that you have to change the validation code to use some other way to report errors than throwing exceptions. For example, you could change:
class Item {
...
void validate() {
if (noHat) {
throw new MyException("bad hat");
}
if (noPants) {
throw new MyException("world-wide pants");
}
}
}
to something like this:
class Item {
...
void isValid(List<MyException> errors) {
boolean ok = true;
if (noHat) {
errors.add(new MyException("bad hat"));
ok = false;
}
if (noPants) {
errors.add(new MyException("world-wide pants"));
ok = false;
}
return ok;
}
}
Messy huh! You could sugar this in various ways, but this style of error reporting is always going to be more complicated. But I don't think there is a practical way to avoid the messiness AND capture ALL of the validation errors.
I am getting an error in NetBeans saying I must throw an SQLException in this method:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
This method is created by NetBeans so it is not allowing me to edit the signature and throw the exception. This is why I created the getCustomerInfo() method. This method does throw the exception, because it uses a method to retrieve information from a database about a customer.
public String getCustomerInfo(int cid) throws SQLException
{
Customer c = proc.getCustomer(cid);
// get info
return "info";
}
The getCustomer method also throws the exception and proc.java compiles.
The exact error is
unreported exception java.sql.SQLException; must be caught or declared to be thrown
In general, if your code needs to throw a type of Exception that the signature doesn't support, and you have no control over the interface, you can catch and rethrow as a type the interface does support. If your interface doesn't declare ANY checked exceptions, you can always throw a RuntimeException:
private void displayCustomerInfo(java.awt.event.ActionEven evt)
{
try
{
int custID = Integer.parseInt(customerID.getText());
String info = getCustomerInfo(custID);
results.setText(info);
}
catch (SQLException ex)
{
throw new RuntimeException(ex); // maybe create a new exception type?
}
}
You almost definitely want to create a new Exception type that extends RuntimeException, and have your client code catch that exception. Otherwise, you run the risk of catching ANY RuntimeException, including NullPointerException, ArrayIndexOutOfBoundsException, etc., which your client code probably can't handle.
Read the error message again, it gives you two choices.
You must either declare the exception as thrown (which you cannot do) or catch the exception. Try the 2nd choice.
You need to put a try/catch block around your call to getCustomerInfo(), like so:
private void displayCustomerInfo(java.awt.event.ActionEvent evt)
{
int custID = Integer.parseInt(customerID.getText());
try {
String info = getCustomerInfo(custID);
} catch (SQLException sqle) {
// Do something with the exception
}
results.setText(info);
}
A couple good options for handling the exception might be: logging the exception and the details used to get it, or using it as a signal to retry the connection request. Alternatively, as Outlaw Programmer shows, you could re-throw the Exception as a RuntimeException of some kind, which removes the requirement of checking.
It does not say you must throw it. It says you can catch it. So use a try/catch block and handle it.
try {
...
}
catch (SQLException e) {
System.out.println("Exception happened! Abort! Abort!");
e.printMessage(); //Not sure if this is the correct method name
}
NetBeans generated components have un-modifiable code, and I'm guessing that it is generated as a part of the gui builder. I'd ask if this was the case, but I can't comment yet. If you select a generated object in the GUI editor, on the right there is a tab "code" that can be used to modify the grayed out area of the code.
Here:
I've come across this problem... been puzzled for the past 2 days.. then I open the source (.java file) with sublime, change the code, save, and it works wonders... I'm laughing when I see this works... think outside the box really works...