Given the following code:
interface Provider
{
String getStuff();
}
class CustomProvider implements Provider
{
public String getStuff() throws RuntimeException
{
// possibly throwing an exception
return "some stuff";
}
}
class Main
{
public static void main(String[] args)
{
Main main = new Main();
main.test(new CustomProvider());
}
public void test(Provider provider)
{
provider.getStuff(); // we don't know that this can throw an exception!
}
}
In this particular case we know it but may not in another situation.
How can we protect from the situation where an implementation of an interface throws an unchecked exception but the client method doesn't know the specific implementation of the interface?
It seems that sometimes with unchecked exceptions you can actually never know if calling a method can throw an exception or not.
A solution could be change the signature of the method in the interface:
interface Provider
{
String getStuff() throws Exception;
}
This will ensure that the clients of that method will be advised that an exception can be thrown in all implementations. The problem with this is that maybe none of the implementations of the interface will actually throw an exception. Also putting a "throws Exception" in each method of an interface looks a bit weird.
It seems that sometimes with unchecked exceptions you can actually never know if calling a method can throw an exception or not.
The compiler doesn't check unchecked exceptions. You can document the constraints of the interface, but they won't be automatically validated by the compiler.
You suggest declaring that the method throws Exception. A more constrained approach would be to declare that the method throws some checked exception.
For example, you could declare specifically that your method may throw an I/O exception, as shown below. Callers then need only handle or throw IOException, rather than many more possible Exceptions.
interface Provider
{
String getStuff() throws IOException;
}
Another option is to declare an ad hoc exception type. This allows the interface to advertise an exception contract with callers, without limiting what kinds of exceptions implementations can encounter.
interface Provider
{
String getStuff() throws ProviderException;
}
class MyProvider implements Provider {
public String getStuff() throws ProviderException {
try {
...
} catch ( IOException e ) {
throw new ProviderException( e );
}
}
}
public class ProviderException extends Exception {
public ProviderException( Exception cause ) {
super( cause );
}
...
}
Related
I have a hard time to understand why the following code compiles, while it is not a subclass of exception:
class Test
{
public void run() throws IOException
{
System.out.println("Test");
}
}
class SubTest extends Test
{
//not a subclass of IOException, still compiles
public void run() throws RuntimeException
{
System.out.println("Test from sub");
}
}
class Sub2Test extends Test
{
//not a subclass of IOException, does not compile
public void run() throws Exception
{
System.out.println("Test from sub");
}
}
I understand RuntimeException is an unchecked exception, but I thought the rule was that it must be a subclass of the parent exception?
Imagine there is a caller which calls Test#run. In the declaration of Test#run, it says it might throw IOException, so the caller knows it can catch and handle it:
Test test = // it could be instance of SubTest of Sub2Test
try {
test.run();
} catch (IOException e) {
}
Then it's ok if SubTest does not throw IOException, the caller will not miss anything.
But if you throw some checked Exception like Sub2Test, since the caller does not know it until runtime, the called is not able to catch and handle it. So it should not be compiled.
"I understand RuntimeException is an unchecked exception, but I thought the rule was that it must be a subclass of the parent exception?"
That is the general rule, as specified in the JLS in section §11.2. Compile-Time Checking of Exceptions, which states (emphasis mine)
The throws clause of an overriding method may not specify that this method will result in throwing any checked exception which the overridden method is not permitted, by its throws clause, to throw (§8.4.8.3).
But that only applies to checked exceptions, and it also explicitly states that
The unchecked exception classes (§11.1.1) are exempted from compile-time checking.
So the compiler is going to ignore the fact that RuntimeException isn't a subclass of IOException.
I have some few doubts on exceptions.
Can anyone tell me why java doesnt allow us to create Checked Exception in a Subclass while it allows Unchecked exception in a subclass
Below exampple throws Compile time error when I use 'throws IOException' , BUT it doesnt throw any error when I use 'throws ArithmeticException' in a subclass.. I just wanna know the actual reason behind it, so can you please?
Here is code (you will get compile time error)
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws IOException {
System.out.println("Child...");
}
}
//using unCheckedException
package com.exception.test;
import java.io.IOException;
public class Parent {
void msg() {
System.out.println("Parent...");
}
public static void main(String[] args) {
Parent parent = new Child();
parent.msg();
}
}
class Child extends Parent {
void msg() throws ArithmeticException {
System.out.println("Child...");
}
}
If a subclass method declares it can throw a checked exception that the parent doesn't, it breaks the Liskov substitution principle, which is one of the corner stones of object oriented programming.
Consider this bit of code, with Child.msg declared to throw a checked exception:
void doMsg(Parent p) {
p.msg();
}
The program semantics break if you pass in a child object because the checked exception is now neither being caught nor thrown: the exception is no longer "checked."
Since unchecked exceptions can be thrown everywhere, declaring to throw one serves no other purpose than documentation. Therefore it can be allowed safely.
The msg() method in your parent class can throw any unchecked exception it likes. Hence, if you explicitly declare that your child throws an unchecked exception, you're not actually altering the contract. Your child method may throw an ArithmeticException, but so might your parent method.
Checked exception can be narrowed down while overriding, but not can't be broaden. Unchecked exception need not be caught by the overridden methods
From the java specs
The checked exception classes named in the throws clause are part of
the contract between the implementor and user of the method or
constructor. The throws clause of an overriding method may not specify
that this method will result in throwing any checked exception which
the overridden method is not permitted, by its throws clause, to
throw.
Unfortunately, you have hit yet another pitfall of Java's misfeature known as Checked Exceptions. The error you are receiving is an actual problem that all Java professionals face: you are implementing a method with some code that happens to throw a checked exception not declared by the superclass method. The declared checked exceptions are a part of the Java method signature; you can reduce the list in a subclass, but you cannot expand it.
If this is more that just a "why" question, and you need a workaround, the standard idiom is
try {
...code that throws the checked exception...
} catch (TheCheckedException e) { throw new RuntimeException(e); }
This is called exception wrapping. If you have more than one or two undeclared checked exceptions, you can also use the opposite idiom, ensuring that all declared exceptions propagate transparently and all undeclared ones get wrapped:
try {
...code that throws various checked exceptions...
}
catch (DeclaredEx1 | DeclaredEx2 | RuntimeException e) { throw e;}
catch (Exception e) { throw new RuntimeException(e); }
I have a base class which implements the following interface, the methods declared on it throw the basic exception type Exception.
There are many concrete classes extending the base class and i dont want to add a try-catch block in all of them. Is there a way to handle throws without adding try-catch?
Interface
public interface IReportFactory {
public Object GetDataFromDB(Connection conn,HashMap<String,String> map) throws Exception;
public Object GetJSONString(HashMap<String,String> map) throws Exception;
}
Base class
public abstract class BaseReport implements IReportFactory{
public Connection conn;
public String acctId = FactoryReport.getAcctId();
------ I WANT TO CATCH EXCEPTION HERE ------
------ WHICH ACCURS IN OTHER CLASSES WHICH EXTENDS FROM THIS CLASSES -----
}
Example of a concrete class (there are 30)
public class GeneralRevenue extends BaseReport {
private final Logger logger = Logger.getLogger(GeneralRevenue.class);
public GeneralRevenue(Connection _conn) {
this.conn = _conn;
}
#Override
public Object GetJSONString(HashMap<String,String> params) throws Exception {
//codes
return jObj.toString();
}
#Override
public Object GetDataFromDB(Connection conn,HashMap params) throws Exception {
//codes
return RevenueList;
}
}
Just because you're extending the interface doesn't mean you have to add throws Exception, it's ok to declare your implementing class as throwing less exceptions than the interface. You just can't make the implementation throw broader exceptions than the interface.
So you could define your methods without the throws clause, like:
public Object GetJSONString(HashMap<String,String> params) {
and if there is any checked exception thrown you can rethrow it as an unchecked exception.
If you want to catch exceptions thrown by the subclass, you have to rearrange your code so that methods of the subclass are called by the super class, otherwise the super class doesn't have the opportunity to catch anything. You might consider if it makes sense to use strategies (which would let you wrap the calls to the strategies and might reduce the amount of inheritance you have to do).
Something that happens a lot is that developers use inheritance as their preferred means of extension, and (since we're always in a hurry) there's not a lot of thought about keeping concerns separated, with the result being code that's complicated and inflexible. Breaking this up along different lines of responsibility might help to make this less complicated and would probably help with the exception-throwing situation, since the different pieces would be better-focused and could throw less broad exceptions.
Why don't you create a custom RuntimeException and throw it inside the try catch block of your base class?
public class GeneralRevenue extends BaseReport {
private final Logger logger = Logger.getLogger(GeneralRevenue.class);
public GeneralRevenue(Connection _conn) {
this.conn = _conn;
}
#Override
public Object GetJSONString(HashMap<String,String> params) throws MyException {
try{
//codes
}catch(Exception e) {
throw new MyException();
}
return jObj.toString();
}
}
class MyException extends RuntimeException {
}
If you throw RuntimeException then there is no need to add the throws declaration. So for Example of you create your own RuntimeException like
class NewException extends RuntimeException{
}
Then when you add RuntimeException to your BaseClass all the other methods will not have to declare throws which will call these methods.
http://docs.oracle.com/javase/6/docs/api/java/lang/RuntimeException.html
when coding. try to solve the puzzle:
how to design the class/methods when InputStreamDigestComputor throw IOException?
It seems we can't use this degisn structure due to the template method throw exception but overrided method not throw it. but if change the overrided method to throw it, will cause other subclass both throw it.
So can any good suggestion for this case?
abstract class DigestComputor{
String compute(DigestAlgorithm algorithm){
MessageDigest instance;
try {
instance = MessageDigest.getInstance(algorithm.toString());
updateMessageDigest(instance);
return hex(instance.digest());
} catch (NoSuchAlgorithmException e) {
LOG.error(e.getMessage(), e);
throw new UnsupportedOperationException(e.getMessage(), e);
}
}
abstract void updateMessageDigest(MessageDigest instance);
}
class ByteBufferDigestComputor extends DigestComputor{
private final ByteBuffer byteBuffer;
public ByteBufferDigestComputor(ByteBuffer byteBuffer) {
super();
this.byteBuffer = byteBuffer;
}
#Override
void updateMessageDigest(MessageDigest instance) {
instance.update(byteBuffer);
}
}
class InputStreamDigestComputor extends DigestComputor{
// this place has error. due to exception. if I change the overrided method to throw it. evey caller will handle the exception. but
#Override
void updateMessageDigest(MessageDigest instance) {
throw new IOException();
}
}
In this case, your super class is not meant to throw an exception.
This is a case where your subclass is thus throwing an exception which is not expected by the overlying software architecture. Thus you can :
update all subclasses to throw exceptions.
wrap the entire Digestor class framework in a new class system.
(simplest) maintain the current code and simply wrap any exceptions you wish to throw in a RuntimeException.
RuntimeExceptions are the idiomatic way to throw exceptions in java which are not checked by the compiler or by method signatures, which occur somewhat unexpectedly.
Your requirements are schizophrenic.
You've got to decide whether the DigestComputor.updateMessageDigest method can, or can not throw IOException. If you want that to be possible, then you must add it to the signature in the base class. That is the only way to force the caller to do something about an IOException. But the downside is that you also force callers of the other subclasses to handle the IOException ... which won't occur.
You cannot create a method override that throws checked exceptions that the overridden method does not. That would break subtype substitutability, and Java doesn't allow it.
It it like a fork in the road. You have to decide to go one way or the other. You can't go both ways at the same time.
However there is a compromise (sort of):
public abstract class Base {
public abstract void method() throws IOException;
}
public class A extends Base {
public void method() throws IOException {
//
}
}
public class B extends Base {
public void method() { // Doesn't throw!!!
//
}
}
Now, if the caller knows that it has an instance of B it can do something like this:
Base base = ...
B b = (B) base;
b.method(); // No need to catch or propagate IOException
(IIRC, the ability to do this ... i.e. to reduce the exceptions thrown in an overriding method ... was added in Java 1.5.)
As someone else suggested, the simplest thing to do would be to simple wrap the real exception in a runtime exception. As a result, you don't have to declare the exception in your throws clause. If you're ambitious enough you can make your own subclass of RuntimeException and catch it at a higher level (this is what hibernate does, it catches all SQLExceptions thrown and wraps them in some subclass of DataAccessException which is a runtime exception).
Suppose I have interface I and two classes A and B that implement it.
The implementation of method f of this interface in A throws one set of exceptions and the implementation in B throws another set. The only common ancestor of these exceptions is java.lang.Exception. Is it reasonable to declare f throwing java.lang.Exception in this case? Any other alternatives?
The reason why I am asking is that on the one hand java.lang.Exception seems too general to me and one the other hand listing all exceptions seems impractical considering possible other implementations.
Example:
interface I {
void f() throws Exception;
}
class A implements I {
public void f() throws IOException {}
}
class B implements I {
public void f() throws InterruptedException {}
}
The reason for using an interface is to abstract away the implementation details.
By throwing these exceptions, you're exposing implementation details that probably should be abstracted away.
Perhaps it would be best to define a new exception. Then each implementation of f() would catch the exceptions it knows about and throw the new exception instead so you'd have:
interface I {
void f() throws MyException;
}
class A implements I {
public void f() throws MyException {
try {
...
} catch (IOException e) {
throw new MyException(e);
}
}
}
class B implements I {
public void f() throws MyException {
try {
...
} catch (InterruptedException e) {
throw new MyException(e);
}
}
}
By wrapping the implementation exception, you're still exposing it to the caller and that can bite you when you're calling remote methods. In those cases you need to do more work to return useful information in a generic way.
Edit
There seems to be a bit of a dispute going on about the correct approach.
When we call f(), we'll need code like:
I instanceOfI = getI();
try {
instanceOfI.f();
}
catch ( /* What should go here ? */ )
It comes down to what is a good Exception class to put in the catch block.
With OP's original code we could catch Exception and then maybe try to see which subclass we have, or not depending on requirements. Or we could individually catch each subclass but then we'd have to add catch blocks when new implementations throw different exceptions.
If we used Runtime exceptions it would come to much the same thing except that we could alternatively defer the exception handling to a caller method without even giving the possibility of exceptions any thought.
If we used my suggestion of using a new, wrapped exception then this means we have to catch MyException and then try to see what additional information is available. This essentially becomes very like just using an Exception, but requires extra work for the limited benefit of having a bespoke exception that can be tailored to the purpose.
This seems a bit backward. You should be throwing exceptions that are relevant and possibly specific to your interface, or not at all. Change the implementations to wrap a common Exception class (although not Exception itself). If you can't deal with this you may want to wrap the Exceptions in the implementations with a RuntimeException.
You could just declare the exceptions you throw
void f() throws IOException, InterruptedException;
If you use a decent IDE, it will correct this for you. I just throw the exception in the method, which the IDE gives the optionsto add to the method clause and its interface.