catch disjonction case exception - java

I have 2 classes:
class MyException extends Exception implements ExceptionManager{
MyException addMessage(String message){...}
}
and
class MyRuntimeException extends RuntimeException implements ExceptionManager {
MyRuntimeException addMessage(String message){...}
}
where
interface ExceptionManager{
ExceptionManager addMessage(String message);
}
I want to do this:
void foo() throws MyException {
try {
...
} catch (MyException | MyRuntimeException e){
throw e.addMessage(...);
}
}
but it doesn't work ; I tried setting ExceptionManager<T extends Exception & ExceptionManager> and T addMessage(String message); or other things but still doesn't work...
Obviously I don't want foo to throw Exception nor set 2 catches and the project is java 11 so no scealed types.
Can't the compiler understand that there's only 2 possibilities for the exception to be thrown, one runtime so I only must declare the other ? Can someone tell me how to do or confirm that it's impossible ?
Thanks

Related

Exception Class declared but not thrown

Here test is not throwing an Exception object , yet i had handled it . Since Exception is an checked exception shouldn't it throw a compiler error of unreachable code in the catch block
class Ece extends Exception {}
public class Excep {
public static void test() { }
public static void main(String[] args) {
try {
test();
} catch (Exception E) {
}
}
}
The class Exception has RuntimeException as subclass. RuntimeException and its subclasses do not need to be declared in methd signature.
In this case you are catching all possible subclasses of Exception, including all that subclasses that do not need signature declaration. If your test method throws for example ArrayIndexOutOfBoundsException you will be able to catch and handle it, yet test signature will not be affected.
Further reading here

EJB wraps all Exceptions into EJBException

Assuming I have a #Stateless bean:
#Local
public interface A {
public void check() throws MyException {
}
#Stateless
public class AImpl implements A {
public void check() throws MyException {
...
try {
data = getDataFromService();
} catch (RException e) {
throw new MyException(e);
}
}
}
Exceptions:
public class MyException extends Exception{}
public class RException extends RuntimeException{}
When I am injecting this bean to some other class with the use of #EJB annotation and executing the check() method, I am getting EJBException with MyException as its cause...
public class B {
#EJB private A a;
public void start() {
try {
a.check();
} catch (MyException e) {
e.printStackTrace();
}
}
}
How can I make it throw proper exception?
Any ideas how to make it work ok?
Is there any way to make it work without intercepting the EJBException throw, and rethrowing its exception cause?
I assume your MyExceptionextends RuntimeException and therefore it is unchecked exception. in such case you can annotate your exception with #ApplicationException annotation. As a result of that your exception will be an application exception instead of a system exception. When a system exception is thrown it is packaged in EJBException, but application exceptions are thrown directly to the client.

How to create a custom exception by extending throwable and using a try-catch block to catch the exception? [duplicate]

Can anyone please explain why we should have constructors like below when defining custom exceptions :
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
It allows you to add to your custom Exception instance information regarding the reason of throwing that exception.
It is useful when you catch one exception and throw another.
For example :
try {
....
}
catch (SomeException ex) {
throw new MyException ("some message", ex);
}
As mentioned in your question one should implement the above mentioned constructors to the MyException class which is a subclass of Exception But it is not absolutely mandatory to have only those constructors.
You can very well have the following constructors which do not have Throwable as parameters:
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
But these constructors have a drawback associated. consider the following code say suppose in class MyClass:
public static void myMethod() throws MyException{
//Some code
}
Now in some code you call this myMethod() as show below:
try{
MyClass.myMethod();
} catch (MyException e){
e.getCause();
}
If you used the constructor with the constructors stated in my answer the e.getCause() would return null. So it would be difficult to ascertain what is the exact cause of the exception.

Interface implementation launches different exceptions

I have an interface
public interface DataDAO {
public void doSomething() throws Exception;
}
Lets say that there are two implementations, one that uses Database to get the data and another one that uses a Webservice.
public class DataDAOJdbc implements DataDAO {
public void doSomething() throws Exception {
//Implement
}
}
public class DataDAOWebService implements DataDAO {
public void doSomething() throws Exception {
//Implement
}
}
As you can already see, the problem is the super generic exception launched. As both implementations need to raise the same kind of exception.
The Jdbc implementation really only raises lets say SQLException while the Webservice implementation only rises the IOException.
Question is, how can I make the interface more elegant, so I capture a proper exception?
The first thing that I though was creating my own exception, and declare it on the interface level
public interface DataDAO {
public void doSomething() throws MyCoolException;
}
And then, of course implement accordinly.
Question is, does this make sense? I have never created my own exceptions, so I am not really sure if this makes much sense or not. Also, what should I take into account when creating MyCoolException?
The first thing that I though was creating my own exception, and declare it on the interface level (...) does this make sense?
Yes, it does makes sense and I would think it is the best way to handle these situations.
I'll provide a kickoff example for this (based on your current code):
public class MyCoolException extends Exception {
public MyCoolException() {
}
public MyCoolException(String message) {
this.message = message;
}
}
public interface DataDAO {
public void doSomething() throws MyCoolException;
}
public class DataDAOJdbc implements DataDAO {
public void doSomething() throws MyCoolException {
//Implement
try {
} catch (SQLException e) {
//handle the exception
logger.error("Error!", e);
//throw your custom exception
throw new MyCoolException(e.getMessage());
}
}
}
public class DataDAOWebService implements DataDAO {
public void doSomething() throws MyCoolException {
//Implement
try {
} catch (IOException e) {
//handle the exception
logger.error("Error!", e);
//throw your custom exception
throw new MyCoolException(e.getMessage());
}
}
}
You can use a generic type to define the interface thrown:
public interface DataDAO<E extends Throwable> {
public void doSomething() throws E;
}
Then your Implementations would look like this:
public class DataDAOJdbc implements DataDAO<JDBCException> {
public void doSomething() throws JDBCException {
//Implement
}
}
public class DataDAOWebService implements DataDAO<WebServiceException> {
public void doSomething() throws WebServiceException {
//Implement
}
}
However, this has the drawback that you can no longer handle all the exceptions the same way, unless you just catch Exception (which pretty much negates the entire point).
does this make sense?
Yes, it does. By declaring that doSomething throws a specific checked exception, you're signaling to callers of the method that they only need to catch and deal with that specific exception. By declaring plain throws Exception, callers would be encouraged to catch and deal with all Exceptions, which even include runtime exceptions like NullPointerException.
what should I take into account when creating MyCoolException?
It could be as simple as the following:
public final class MyCoolException extends Exception {
public MyCoolException(Throwable cause) {
super(cause);
}
}
So your custom exception would simply act as a wrapper for the cause exception, whatever it may be. If possible you could add a message with additional information that might be helpful for debugging. When MyCoolException is caught you can unwrap it by calling getCause(), or else pass it into a call to a logging framework (its stacktrace will include the cause exception).

Java interface throws an exception but interface implementation does not throw an exception?

I read this code where the interface throws an exception, but the class which implements it doesn't throw one or catch one, why is that? Is it legal or safe in java?
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{
public String sayHello() {
return "Server says, 'Hey'";
}
public MyRemoteImpl() throws RemoteException {}
public static void main (String[] args) {
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind("RemoteHello", service);
} catch(Exception ex)
{
ex.printStackTrace();
}
}
}
A general rule of implementing and extending is you can make your new class or interface "less restrictive" but not "more restrictive". If you think of the requirement to handle an exception as a restriction, an implementation that doesn't declare the exception is less restrictive. Anybody who codes to the interface will not have trouble with your class.
— Stan James
As part of the discussion at http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface
If a Java method overrides another in a parent class, or implements a method defined in an interface, it may not throw additional checked exceptions, but it may throw fewer.
public class A {
public void thrower() throws SQLException {...}
}
public class B extends A {
#Override
public void thrower() throws SQLException, RuntimeException, NamingException {...}
}
SQLException is fine; it's declared in the overridden method. It could even be replaced by a subclass like SerialException.
RuntimeException is fine; those can be used anywhere.
NamingException is illegal. It isn't a RuntimeException, and isn't in A's list, even as a subtype.
Great answer by #Chetter Hummin.
One way to look at this, and I find it easy to remember, is interface's implementations can be more specific but not more general.
For example in interface void test() throws Exception means "test may throw exception"
then implementation can be void test() means "test will not throw exception" (more specific)
or implementation can be void test() throws NullpointerException (more specific)
interface x {
void testException() throws Exception;
}
public class ExceptionTest implements x {
#Override
public void testException() { //this is fine
}
////// or
#Override
public void testException() throws NullPointerException { // this is fine
}
}

Categories