First of all I am not really sure what exactly the reason for this behaviour is, so the title might be wrong.
I have one "MainClass" which creates a new Object of a "SubClass" by using the Method.invoke() method (with a because there are several "SubClasses" all having the same method, if you a better way of solving this, I would appreciate it). As exceptions thrown by the invoke() method needs to be caught I have a try {} catch () {} around it. Now it seems like when one of the "SubClasses" throws an error and it is not directly in the code below a try block, it does not catch it but instead the "MainClass" catches it.
I don't know if this is the intended behaviour, but I would appreciate a way to prevent this from happening.
Example:
MainClass invokes method of SubClass
Method tries for example to do this new Gson().fromJson("Test",ArrayList.class); in a try block
MainClass catches the Exception
Apprently the problem was not Gson. What happeneds was that the
try {
new Gson().fromJson(...);
}
catch (Exception e) {
logThatError();
}
Correctly catched an Exception thrown by Gson but the logThatError() caused an Exception as well.
Related
Let me preface this by saying, I am not a Java programmer and have thus far been unable to understand WHY this is the case.
I'm currently working on a homework assignment that requires me to create a basic GUI using JavaFX. The functionality of this GUI requires that there are buttons that will perform CRUD operations when clicked. Currently I have everything set up properly in my Insert method:
public void Insert() throws SQLException{
//Insert new record here
}
However, whenever I try to subscribe to this method using 'setOnAction', the compiler is telling me there's an unhandled exception on the event:
btnInsert.setOnAction(e ->Insert());
I'm more curious if there's a way to handle this in a relatively succinct way? I've thus far been unable to come up with a solution.
That's because Java requires you to declare all checked exceptions you throw - so whenever you call a method that may throw a checked exception, you must either catch it or declare you may throw it yourself.
See this question for an explanation of checked vs. unchecked exception (The short version - any Exception which inherits either Error or RuntimeException is unchecked, while all other exceptions are checked.)
When you are providing setOnAction with a lambda, you are actually creating an anonymous class implementation of EventHandler<ActionEvent>. Since it does not declare it throws any exceptions, neither does your anonymous class (and in fact - it can't).
So you have two options of solving the problem:
Catch and handle the exception:
btnInsert.setOnAction(e -> {
try {
Insert();
} catch (SQLException ex) {
// Log error, show error message, etc... Whichever is applicable for your application
}
});
Rethrow an un-checked exception:
btnInsert.setOnAction(e -> {
try {
Insert();
} catch (SQLException ex) {
throw new RuntimeException(ex); // Or any other subclass of RuntimeException or Error
}
});
As to choosing between the two options - Oracle's documentation says this:
Here's the bottom line guideline: 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.
Of course, this could all be moved away from the actual EventHandler, so it can be called on a method that is checked-exception-free.
Suppose we a have class named DynamicClass:
public class DynamicClass {
public void get(String input) {
System.out.println(input);
}
}
Now, imagine the following instantiating of DynamicClass:
DynamicClass clazz = new DynamicClass();
clazz.getName();
clazz.getOther();
Of course, the calling of getName and getOther methods throws MethodNotFoundException exception. However, I'm curious, is there any way to catch the MethodNotFoundException exception inside the DynamicClass class, i.e. the calling of get("Name") and get("Other") rather than throwing the MethodNotFoundException exception due to the calling of getName() and getOther()?
Nice curiosity.
I am afraid, there is no other way than using try catch in Java, but if Java was a OTF(on the fly) compiler and the exception mechanism actually use a (if-responds_to?) method which expected to be declared on the top of the hierarchal pyramid of Class inheritance for example Object in Java that would be possible to override that method on your DynamicClass.
However Java doesn't use the above mechanism to control the if responds_to? and the messages which are sent to an object(class) are tested somewhere else in compiler but not as a method that you can override.
I know a language called (Magik) that has the above mechanism which is very nice and it is an OTF compiler.
the Object class in Magik has a method with name does_not_responds_to() and whenever a message is sent to an object it is tested against the class states and behaviors and finally raise or better to say run does_not_responds_to() method in case the method name(message) is invalid.
It is a very neat solution to implement the does_not_responds_to? method in the class (DynamicClass) to handle the exception before it raises. however after 10 years of experiance with Magik, never needed to do so.
Sorry, My English is not good, I hope I could explain the issue.
Why not?
try{
clazz.getName();
clazz.getOther();
}catch(MethodNotFoundException e){
clazz.get("Name")
}
But actually do not think that it is good idea...
With reference to this answer, it's possible to catch all uncaught Exceptions in Java:
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable throwable) {
// TODO
}
});
I was playing around with some of my code and came across something I didn't fully understand. I have a class called SentimentClassifier, the constructor of which looks like this:
public SentimentClassifier(final int nGramToBeUsed) {
try {
classifier = (DynamicLMClassifier<?>) AbstractExternalizable.readObject(new File(etc));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I have another class which creates this one, like so:
public TwitterManager(final int nGramToBeUsed) {
sentimentClassifier = new SentimentClassifier(nGramToBeUsed);
}
If I run the code like this, everything works fine. But if I change the first class from using try/catch to throw the exception, like so:
public SentimentClassifier(final int nGramToBeUsed) throws ClassNotFoundException, IOException {
classifier = (DynamicLMClassifier<?>) AbstractExternalizable.readObject(new File(etc));
}
Suddenly the second class complains that the IOException isn't being handled. Why is this thrown only for the thrown exception and not for the try/catch?
When you call a method M1 from another method M2:
If some code in M1 raises some Checked Exception, and the method M1 itself handles it, rather than throwing it, you don't have to worry about the exception while calling it.
Now, if the exception raised in M1, is not being handled in M1 itself, rather it is propagated up the stack trace, then M1 must declare that exception in the throws clause. This is just for the convenience of the calling method to know that it should be ready to handle those exception in case they are thrown. This is only the case with Checked Exception.
But if the calling method M2, doesn't handle that exception, it has the option to re-declare that exception to be thrown in it's own throws clause, in which case the exception will be propagated further up the stack trace.
If method M2 does neither of the previous two task, you will get a compiler error. Because you haven't given any proper path or way to handle the exception that can be thrown.
Note all the above arguments are true for Checked Exception only. For Unchecked exception, you don't need to handle it yourself, neither you need to declare it in throws clause.
Suggested Read:
Java: checked vs unchecked exception explanation
Unchecked Exception controversies
JLS - The Kinds and Causes of Exceptions
In Java, if a method declares that throws an Exception (other than RuntimeException), callers must handle the exception. They can do this one of two ways: catch it, or declare that they themselves throw it.
You moved the handling of these two exceptions from the SentimentClassifier constructor to its callers.
If the constructor declares any exceptions, the calling code must handle them or declare them. After all, the constructor could throw/propagate these exceptions, and any code that calls it must handle them.
When you catch an exception, it means that you will deal with it on the catch block, and its consequences, so the external code can continue to progress without being warned about the internal exception.
If your exception is thrown, you are forcing by contract to any creator/invoker class to deal with any declared exception that could be produced during the initialization/execution process, as it can be critical for the business logic.
In this case, if the exceptions that can be generated during init are critical, and could stop the class from working properly, they should be thrown, as the creator class TwitterManager could have a disfuncional or partially initialized instance of the SentinelClassifier object, leading to unexpected errors.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Throws or try-catch
I'm writing an API and I wish to write code such that I can raise an exception in a particular scenario. I've created an exception class as follows :-
public class InvalidSeverityException extends Exception {
private static final long serialVersionUID = 1L;
public InvalidSeverityException() {
// TODO Auto-generated constructor stub
}
}
In the codebase im having the following to call the code :-
throw new InvalidSeverityException();
However Eclipse suggests that I either use throws or enclose it within a try ... catch block. I feel that I shouldn't be catching this error and that the developers who use my API should enclose the code within try...catch.
Does that make sense? Am I doing something wrong?
When handling with exceptions in Java you must understand the concept of checked exceptions and unchecked exceptions.
In your case currently you are defining a checked exception, maybe you want an unchecked one.
Here's a brief description about each one of the types:
Checked Exceptions
This exceptions must be part of the method's signature that raises them (or that invokes one method that does) or you must catch them with a try catch block and deal with the problem. Usually checked exceptions are used when there is something that can be done about the error and also when you want the developer to be aware that such error may occur and that has to be handled.
In java java.lang.Exception is a checked exception and all its subclasses will also be checked.
Unchecked Exceptions
This exceptions on the other hand don't need to make part of the method signature, nor you have to wrap methods that throw new in a try catch block. It's just expected that somewhere in the call stack there will be a try catch to handle it, otherwise if it reaches the JVM it will nicely dump you a stacktrace.
In java java.lang.RuntimeException is an unchecked exception and so are all its subclasses.
My opinion
If you are defining an API my suggestion is to use checked exceptions, this is mostly because you explicitly inform the developers using your API that such an exception might occur (so they can handle it anyway they want).
You are correct, you should not catch it. As suggested by eclipse, you should use throws so that the developers will know that your method potentially throws that exception and can then catch it.
.... method() throws YourException{
The method where you have throw new InvalidSeverityException(); should define throws InvalidSeverityException
Example:
void yourMethod() throws InvalidSeverityException
{
........//Some code
throw new InvalidSeverityException();
}
Well then surely you follow the first suggestion by Eclipse and set your method to throw the exception.
public void myMethod() throws InvalidSeverityException {
//throw it somewhere in here so that other
//developer can catch it while calling your method
}
I have a fairly standard creational pattern whereby a class exposes a static method for returning instances of itself, like so:
public class MyClass {
private MyClass(/*parameter list*/) {
// internal construction
}
public static MyClass GetMyClass(/*parameter list*/) {
return new MyClass(/*parameter list*/);
}
}
...
//this line wont break in the debugger and seemingly never gets called - why?
MyClass inst = MyClass.GetMyClass(/*parameter list*/);
However, inst is always null. I can't break on the line that calls the static method, the debugger just ignores it - what's going on?
Edit: Thanks for the suggestions.
All projects have been cleaned and rebuilt (manully in NetBeans)
I have added a break in the static method and no it isn't hit.
Yes, the code above is being called (ultimately) in a constructor for a Swing 'FrameView' though it surely shouldn't matter where I am calling this from, should it?
There is no exception swallowing anywhere
Side note, other than the missing class declaration (which was a typo) why is this not valid Java? Why is this obviously C# code? Explanations would be more helpful than downvotes :)
Edit II: The Params is just supposed to indicate a whole load of parameters - sorry if this confused anyone, I obviously know parameters have type declarations and so on, the code above was intended as a quick shorthand version rather than a full and (complicated) real sample...
A couple of options:
An exception is being thrown which you're somehow missing
You're not debugging the code that you think you are (i.e. your built code is out of date with your source code)
The latter is the most likely one, IMO.
Apparently you're swallowing an exception inside the constructor something like:
try {
// Something.
} catch (Exception e) {
}
You should never do that. It makes debugging and nailing down the root cause much harder. Rather throw it or at least do a e.printStackTrace(). If throwing and you don't want to use the throws clause for some reasons, consider using a RuntimeException (or one of its subclasses). E.g.
try {
// Something.
} catch (Exception e) {
throw new RuntimeException("Construction failed.", e); // Try to be more specific, e.g. IllegalArgumentException or so. Or just write robust code, i.e. nullchecks and so on.
}
or (but in my opinion not very applicable in your case):
try {
// Something.
} catch (Exception e) {
e.printStackTrace();
}
I understand that you are trying to make a simple example to show your problem, however if you add the appropriate type statements into your sample code, then it both compiles and does what you expect.
However, in your original codebase you could simply place the breakpoint in the static method to see whether or not it is called.
Maybe a simple question, but you never know… are you sure that you are running the code that you think you are running? That is, is everything recompiled and built from the latest sources?
There is nothing wrong with :
MyClass inst = MyClass.GetMyClass(Params);
It depends what is before or after that line of code.
Start by doing this:
public class MyClass
{
private MyClass(/*parameter list*/)
{
System.out.println("entering MyClass(...)");
// internal construction
System.out.println("leaving MyClass(...)");
}
// Java uses lower case for method names - so get not Get
public static MyClass getMyClass(/*parameter list*/)
{
final MyClass foo;
System.out.println("entering getMyClass(...)");
foo = new MyClass(...);
System.out.println("leaving getMyClass(...)");
return (foo);
}
}
...
MyClass inst = MyClass.getMyClass(/*parameter list*/);
See if outside the debugger the code gets called.
If you are catching any exceptions, at the very least do:
catch(final WhateverException ex)
{
// at the very least do this so you can see that the exception happens
ex.printStackTrace();
}
Avoid catching Throwable, Error, Exception, and RuntimeException. Infact the best way do do it is get rid of all the catch statements and then only add catches for what the compiler tells you that you have to have.
The other thing is you do not say where MyClass inst = MyClass.getMyClass(/parameter list/); is called from. It is entirely possible that that line never gets hit.
You mention that you're calling this from the constructor of a FrameView, but I assume you're talking about an implementation or extension of that interface/object. My reasoning was to make sure you wern't recursively invoking the constructor.
I think the reason why catching java.lang.Exception isn't catching the problem is because it is likely too specific in this case. Try catching java.lang.Throwable which will catch errors like java.lang.NoClassDefFoundError - that frequently crops up when you have a jar missing somewhere.