Can we create an custom exception for a class Level.
For example I have a Class A, now when I create a given object or When I call a given method, I would like yo throw my custom exception.
This is the easiest way to create your own Exception:
public class LevelException extends Exception {
public LevelException(String message) {
super(message);
}
}
You have two kind of exceptions checked and unchecked exceptions.
Unchecked exceptions are the sub classes of RuntimeException, those exceptions don't need to be added explicitly in your method/constructor description, calling code doesn't have to manage it explicitly with a try/catch block or by throwing it.
Checked exceptions are the sub classes of Exception but not the sub classes of RuntimeException, those exceptions need to be added explicitly in your method/constructor description, calling code have to manage it explicitly with a try/catch block or by throwing it.
Depending of your need, you will chose one of the two possibilities, if you want to enforce calling code to manage it, use checked exceptions otherwise use unchecked exceptions.
Unchecked exceptions
How to create it:
public class MyException extends RuntimeException {
...
}
How to use it:
public void myMethod() {
...
if (some condition) {
throw new MyException();
}
...
}
Checked exceptions
How to create it:
public class MyException extends Exception {
...
}
How to use it:
public void myMethod() throws MyException {
...
if (some condition) {
throw new MyException();
}
...
}
You can find more details about exceptions here
Related
So picture the following scenario. I have two sets of classes and interfaces. ClassA, ClassB, ClassAInterface, and ClassBInterface. ClassA uses ClassB in several of its methods. These methods from ClassB occasionally throw exceptions.
public class ClassA implements ClassAInterface {
public void example() {
ClassB test = new ClassB();
ClassB.exampleTest();
//more code using ClassB
}
}
public class ClassB implements ClassBInterface {
public void exampleTest() throws ExampleException() {
boolean tru = false;
if (tru) {
throw new ExampleException();
}
}
}
So the problem that I'm having is that I'm getting an Unhandled Exception type ExampleException() error in the ClassA.example() method. Why does this happen? I want the ClassB method to throw the exception in specific cases, and signify that it sometimes throws exceptions with throws ExampleException(), so why does ClassA not compile. To solve it, I can't add a throws statement onto ClassA.example() because it would violate ClassAInterface. And if I just wrap ClassB.exampleTest() in a try catch statement, much of the rest of ClassA.example() would throw errors because ClassB signifies something is wrong and you should throw an exception at that point, which is the entire point of throwing an exception`. So I'm not sure why this is happening or how to solve it.
Why does the code refuse to compile?
It's quite normal. As you said, B.exampleTest() sometimes throws an exception. A.example() calls B.exampleTest() and does not catch any exception. So, even if the exception doesn't always happen, it happens sometimes. And when it happens the exception is also thrown by A.example(). So it has to be declared or caught. Just like B.exampleTest() sometimes throws an exception, A.example() also sometimes throws the same exception.
Now, what to do? You have 3 choices:
declare that the exception is thrown: the caller of A.example() will then have to decide what to do in that case.
catch it inside A.example(), and deal with it somehow.
catch it, wrap it inside a runtime exception (which doesn't have to be declared in the throws clause), and throw this runtime exception. The caller will have to deal with this runtime exception, but won't have any hint from the compiler that an exception can be thrown.
I'm using Netbeans 8 IDE and I just came to this odd situation. Let's say I've a method in a class that throws and Exception and when I call that method Netbeans does not enforce the try catch. Sometimes an Exception may occur and it is not catch.
Why isn't Netbeans enforcing the try catch method?
Here's an example:
public class MyMethodClass {
public MyMethodClass() {}
public void someMethod() throws NullPointerException {
// do something
if(something == null) {
throw new NullPointerException();
}
// do something else
}
}
public class MyClass {
public MyClass() {
MyMethodClass mmc = new MyMethodClass();
// Here Netbeans does not force me to use a try catch, why?
mmc.someMethod();
}
}
NullPointerException is an unchecked exception, which means that you don't always need to catch it. Unchecked exceptions are those which extend RuntimeException or Error. The main purpose of these is for cases where there usually is no recovery; methods aren't required to declare unchecked exceptions either. This is perfectly valid:
public void throwNPE() {
throw new NullPointerException();
}
Here is one of Oracle's statements on checked vs unchecked exceptions.
NullPointerException is an unchecked exception (since it's a subclass of RuntimeException). You don't have to catch unchecked exceptions for the code to compile.
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary
Because NullPointerException is an unchecked exception.
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.
I am trying to add a custom throws clause to a method definied by an interface. This is not possible. How could I bypass it? Here is some code:
private void sendRequestToService(final ModuleRequest pushRequest)
{
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName name, IBinder service)
{
try
{
//some lines..
} catch (RemoteException e)
{
throw new RuntimeException(new UnavailableDestException()) ;
}
}
};
}
Any idea how I could throw my custom exception?
There are two types of exceptions, checked and unchecked. Any Throwable is either one or the other.
An example of a checked exception is IOException; probably the most (in)famous unchecked exception is NullPointerException.
Any checked exceptions that a method may throw must be declared in its throws clause. When you #Override a method (either implementing an interface method or overriding an inherited method from a superclass), certain requirements must be met, and one of them is that the throws clause must not cause a conflict. Simplistically speaking, subclasses/implementations can throw LESS, not MORE checked exceptions.
An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause.
So in this particular case, if you want to throw a CustomException in an implementation of an interface method that does not list it in its throws clause, you can make CustomException extends RuntimeException, making it unchecked. (It can also extends any subclass of RuntimeException, e.g. IllegalArgumentException or IndexOutOfBoundsException may be more appropriate in some cases).
This will allow you to compile the code as you desire, but note that the choice between choosing checked vs unchecked exception should not be taken too lightly. This is a contentious issue for many, and there are many factors to consider other than just getting the code to compile the way you want it. You may want to consider a redesign of the interface rather than having implementors throwing various undocumented unchecked exceptions not specified by the interface contract.
References
JLS 11.2 Compile-Time Checking of Exceptions
JLS 8.4.6 Method Throws
A method that overrides or hides another method, including methods that implement abstract methods defined in interfaces, may not be declared to throw more checked exceptions than the overridden or hidden method.
Related questions
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
The case against checked exceptions
See also
Effective Java 2nd Edition
Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
Item 59: Avoid unnecessary use of checked exceptions
Item 60: Favor the use of standard exceptions
Item 61: Throw exceptions appropriate to the abstraction
Item 62: Document all exceptions thrown by each method
Workaround "solution"
If a redesign is impossible, then wrapping your CustomException in a RuntimeException (or its subclass) will "work". That is, instead of:
// ideal solution, not possible without redesign
#Override public static void someMethod() throws CustomException {
throw new CustomException();
}
//...
try {
someMethod();
} catch (CustomException e) {
handleCustomException(e);
}
You can, should you insist, do the following:
// workaround if redesign is not possible
// NOT RECOMMENDED!
#Override public static void someMethod() {
throw new RuntimeException(new CustomException());
}
//...
try {
someMethod();
} catch (RuntimeException e) { // not catch(CustomException e)
if (e.getCause() instanceof CustomException) {
handleCustomException((CustomException) e.getCause());
} else {
throw e; // preserves previous behavior
}
}
It needs to be reiterated that this is NOT a recommendable technique in general. You should fix the problem at the design level if at all possible, but barring that, this is indeed a possible workaround.
Throw a RuntimeException.