Cannot cast from Throwable to MyException - java

I am catching an Exception and trying to examine the getCause() of it, performing some further actions if the cause is a of type MyException, defined in another library.
I am getting this Eclipse (compiler?) error when trying to check if e.getCause() instanceof MyException:
Incompatible conditional operand types Throwable and MyException
When attempting to cast (MyException) e.getCause(), I get:
Cannot cast from Throwable to MyException
I can compiled e.getCause().getClass().equals(MyException.class), and this does return true.

The solution is that MyException inherited from an Exception in an external library, but the top-level project didn't include that external library. I discovered this when I created a private class that extended MyException, and got an inconsistent type hierarchy error.

Related

Which Java Runtime Exception to Use When Missing an InitialContext Definition

I am programming a Java Servlet application which needs certain environment variables and JNDI definitions to be present. These are defined in server.xml file. Using default values is not possible. So the program needs to throw a runtime (unchecked) exception. But which one? If none of the subclasses of java.lang.RuntimeException is suitable, I guess we will need to create a new type.
You could use exceptions already defined, but I just usually implement my own, because I can always quickly recognize it when it is thrown. (It tells you more, just by having your project's classpath.)
public class MissingInitialContextException extends RuntimeException {
public MissingInitialContextException() {
}
public MissingInitialContextException(String message) {
super(message);
}
public MissingInitialContextException(String message, Throwable cause) {
super(message, cause);
}
public MissingInitialContextException(Throwable cause) {
super(cause);
}
public MissingInitialContextException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
You can auto generate classes like this in most IDE. (IDEA, after you created the class, ALT+ENTER and override methods from the RuntimeException class)
Why use custom exceptions.:
You can use your IDE's find implementations and other search functions to locate usages
In some frameworks, like in Spring Boot, you can decorate your exceptions with annotations and quickly define the response text and http error code.
You can change the exception's implementation later.
You can define automatic break on exception in your IDE for your custom exception, while if you would do this for a built in one, your debugger would stop in unexpected lines.
You can avoid unintentionally catching other library's exceptions.
java.lang.NullPointerException
When the configuration of the application is not (yet) complete the variables will probably be null, a NullPointerException seems appropriate. This exception is pretty generic but can be customized with a specific detail message in the constructor.
From the API:
Applications should throw instances of this class to indicate other illegal uses of the null object.
When accessing or modifying the field of a null object.
throw new NullPointerException("environment variable XX is missing");

SonarQube error: Refactor this method to throw at most one checked exception

I am using SonarQube and it shows the following error:
Public methods should throw at most one checked exception.
// Noncompliant
public void delete() throws IOException, SQLException { /* ... */ }
// Compliant
public void delete() throws SomeApplicationLevelException { /* ... */ }
Does this means, SomeApplicationLevelException is a parent class and IOException and SQALException are derived from it? And we should throw the parent class exception? Thereby adhering to method throwing only 1 checked exception?
Because I have 2 exceptions that i have defined say for example Exception1 and Exception2 that extend Exception. And my method say, sampleMethod() throws them i.e,
public void sampleMethod() throws Exception1, Exception2 {
}
And the error is shown here. So should I have one class as parent (say MainException) and derive Exception1 and Exception2 from it and throw parent exception class? Like below:
public void sampleMethod() throws MainException {
}
Is the above solution proper?
If you have a method in your application that is declared as throws SQLException, IOException, you are probably leaking internal implementation details to your method's users. Specifically, you're saying:
Your method is implemented using JDBC and file I/O. Your users don't care how your method is implemented; they only care about what your method does.
Your method, including any future version of it, will never throw any other checked exception. If in future you change your method so that it might throw another checked exception, it will break backwards compatibility.
The advice is to create your own application-specific class (derived from Exception), and only throw that in your method. You can, if you like, wrap the SQLException or the IOException (or any other exception) inside your application-specific exception as the cause.
Note, however, that there is a school of thought that says Java checked exceptions are a bad idea (and one of the reasons C#, and more modern languages such as Kotlin, don't have checked exceptions).
UPDATE: the above answer related to the first version of the question (edit #1). The question was subsequently updated to point out that the two thrown exceptions were application-defined ones, so therefore much of the above rationale no longer applies. The answer to the updated question is explained in this post.
IOexception and sqlexception both are checked exception s,totally different from each other , now if we extend both from one exception and throw the parent exception , which is not a mandatory in java, it will be kind of misguiding the user of the api.
However, if you want to do it in ur app to avoid sonarqube error , you can catch all your specific exceptions and throw a custom exception wrapping the original exception information in exception message.
for example
try{
///piece of code that throws IOException and SQLException
}catch(IOException | SQLException ex){
throw new DataException(ex,"Any customized message you want");
}
This DataException will then will be included in the throws clause of method signature having this try catch.
DataException extends Exception class and by passing ex in the contructor you are wrapping the original exception in custom exception with your original exception info preserved.

Unhandled exception type Exception

This is a simplified class that describes my problem:
public class Main {
enum Test{
First(method()){ // Unhandled exception type Exception
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
}
Above someCondition depends on device and some situations and I can not decide in about it now, also as you can see, I do not want to catch Exception in method.
Yes. It is a compilation error.
No. There is no special syntax to deal with this.
I do not want to catch Exception in method.
Unfortunately if you throw a checked exception, it has to be caught further up the call stack. That is a fundamental design principal for the Java language, and one that the compiler enforces strictly.
In this, case there is no way to catch the checked exception. Hence, if you are going to call a method in enum constant parameter (as per your code), the method cannot throw a checked exception1.
Here is a possible workaround, though this is probably a bad idea:
public class Main {
enum Test{
First(methodCatchingException()){
// ...
};
Test(Object obj){
//...
}
}
static Object method() throws Exception{
// ...
if (someCondition){
throw new Exception();
}
}
static Object methodCatchingException() {
try {
return method();
} catch (Exception ex) {
throw new SomeRuntimeException("the sky is falling!", ex);
}
}
}
Another way to look at this problem is to ask yourself what should happen with the exception if the compiler let you write that ... and an exception was thrown? Where would it go?
You can't catch it ... because the enum initialization is like a static initialization.
If the Java runtime completely ignored the thrown exception, that would be really bad.
If the Java runtime crashed, then the model of checked exceptions is broken.
So, what this is saying to me is that the Java language design is right, the Java compiler is right ... and the real problem here is in your application design:
You should not be propagating a checked exception here. If an exception occurs in this context it is categorically NOT a recoverable error.
Maybe it is inadvisable to use an enum for this ... because of the potential for non-recoverable initialization errors.
(Note that if this method call terminates due to an unchecked exception, it will turn it into an ExceptionInInitializerError. In addition, the JVM will mark the enum class as uninitializable, and will throw an NoClassDefFoundError if your application attempts to use it; e.g. via Class.forName(...).)
I assume that Exception is used here for illustration purposes. It is a bad thing to declare methods as throws Exception or to throw new Exception(...)
1 - I had a look at the JLS for something to back this up. As far as I can tell, the spec does not mention this situation. I'd have expected to see it listed in JLS 11.2.3. However, it is clear that a compiler cannot allow a checked exception to propagate at that point as it would "break" the model of how checked exceptions work.
I don't think you want to be throwing a checked exception here (which is what Exception is). The reason: you're invoking the call of method inside of the constructor of Test. There's really not a clean way to deal with it.
While the obvious choice here is to switch to RuntimeException, I want you to reconsider throwing the exception in the first place. Since your enum will only ever have First declared in it, does it really make sense for it to throw an exception when it's being instantiated? Personally, I don't think it does; whatever dangerous operation it's doing should be deferred until you want to invoke it, and then would you want to throw your exception.

Which all comes under unchecked exception?

I had a discussion with one of the seniors on Exception in Java on concept
If I create a class by extending Exception class then it will be checked exception
If I create a class by extending Throwable,RuntimeException, or Error, then it will be unchecked Exception
Is the above statements correct ?
Note: I have through this link When to choose checked and unchecked exceptions
EDIT:
While going through the answer #Daemon, he says
'Throwable on the other hand, is extended by Exception, and is therefore a checked exception.'
I have a question : Throwable is extended by Error also, so why not it is Unchecked ?
Anything that extends Exception but does not extend RuntimeException. Error and Throwable should not be used by Java programs, as Error is intended to communicate serious, unrecoverable problems such as completely running out of memory, hardware problems, or the like.
Technically, only classes that extend Exception are exceptions; Errors and other Throwables are not exceptions and are not expected to be caught by regular programs.
You are correct that any class extending Exception will be a checked exception, however you are mistaken with your next statement:
If I create a class by extending Throwable,RuntimeException, or Error, then it will be unchecked Exception
If you extend RuntimeException or Error, your class will be a unchecked exception.
Throwable on the other hand, is extended by Exception, and like Exception is a checked exception.
The below code demonstrates these practically. For more information, Barry Ruzek's "Effective Java Exceptions" makes for some very interesting reading on the subject.
public class JavaExceptions {
public static void throwException() throws Exception {
throw new Exception("This is a Checked Exception.");
}
public static void throwRuntimeException() throws RuntimeException {
throw new RuntimeException("This is a Runtime Exception.");
}
public static void throwError() throws Error {
throw new Error("This is an Error.");
}
public static void throwThrowable() throws Throwable {
throw new Throwable("This is a Throwable.");
}
public static void main (String... args) {
//Exception extends Throwable, thus both are checked Exceptions.
try {
throwThrowable();
throwException();
} catch (Throwable e) {
//Handle exception (or throwable in this case)...
e.printStackTrace();
}
//RuntimeException and Error are both unchecked exceptions.
throwRuntimeException();
throwError();
}
}
EDIT 1: In regards to Error and its use, this is taken from Oracle's Documentation:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur. That is, Error and its subclasses are regarded as unchecked exceptions for the purposes of compile-time checking of exceptions.
EDIT 2: The classes we are dealing with here can be described as follows:
Throwable extends Object: Top-level class that should be extended by any class that needs to be thrown (like Exceptions and Errors). Throwables are checked. See: Throwable (Java Platform SE 7)
Error extends Throwable: A subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Overides Throwable functionality to become unchecked. See: Error (Java Platform SE 7)
Exception extends Throwable: Another subclass of Throwable that indicate conditions that a reasonable application might want to catch. Like Throwable, is checked. See: Exception (Java Platform SE 7)
RuntimeException extends Exception: The superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. Overrides Exception functionality to become unchecked. See: RuntimeException (Java Platform SE 7)
From the oracle documentation: "For the purposes 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. " So, your first statement is correct, the second is not.
You can read more in the SCJP Sun Certified Programmer for Java 6 pg. 356-380.
If I create a class by extending Exception class then it will be
checked exception
This is Correct.
If I create a class by extending Throwable,RuntimeException, or Error,
then it will be unchecked Exception
This is incorrect. The class RuntimeException and its subclasses, and the class Error and its subclasses are unchecked exceptions classes. Because the compiler doesn’t forces them to be declared in the throws clause. All the other exception classes that are part of Throwable hierarchy are checked exceptions.
Exception class and Error class both extends Throwable class. RuntimeException class extends Exception class. Checked exceptions should be handles using try catch or throws in compile time. No need for that handling for RunTimeExceptions. Errors should not be handled but let them occur cause they are serious things.

Unhandled Exception error unresolved compilation

public void useSkill(Champion target, int skillIndex, boolean enemy) throws UtilitiesException {
if (champSkills[skillIndex].getManaCost() > this.currentMana) {
throw new RequirmentNotMetException("Not Enough mana");
}
I would like to throw a requirmentNotMetexception (which extends the utilitiesException) with message "not enough mana".
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type UtilitiesException
at eg.edu.guc.lol.game.champions.Tank.useSkill(Tank.java:27)
at eg.edu.guc.lol.game.champions.asfasf.main(asfasf.java:33)
I want to use exceptions to show the user that the champion has no mana instead of using an if/else statement checking the mana of the champion and printing not enough mana.
Somebody in the call stack has to handle the RequirmentNotMetException, or every method on the call stack has to declare that it throws the exception (or a parent), or the exception has to extend RuntimeException. Evidently, your main method is not declared as throwing it, and I wouldn't expect it to. So, check up the call chain, identify who should handle the exception, have that method handle it, and have everything in between declare itself as throwing it.
Your useSkill method looks fine. It declares the exception type in the throws clause of the method signature, so the problem is likely where this method is invoked. It looks to me like you're getting the error runtime, which might indicate that you have not recompiled all the classes using the Tank class after you have changed the signature. Still, you need to either catch the exception where you're using the useSkill method, or just pass it on by declaring those methods to throw that exception type as well.
Either you have not imported the UtilitieException or your UtilitiesException class has errors.

Categories