change method to Runtime Exception in java - java

I have a method, in which right now I am handling the exception using the try catch method.
I have a custom exception method to handle the error.
Now I have to change this exception handling to runtime exception.
Code:
public class AppException extends RuntimeException {
private static final long serialVersionUID = -8674749112864599715L;
public AppException() {
}
public AppException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public AppException(String message, Throwable cause) {
super(message, cause);
}
public AppException(String message) {
super(message);
}
public AppException(Throwable cause) {
super(cause);
}
}
Method which handled using try catch.
#Transactional(readOnly = false)
#Override
public String save(StagingDocument stagingData)
throws AppException {
String enrichObjectId = null;
try {
EnrichDocument document = getEnrichDocument(stagingData);
EnrichDocument enrichPayload = enrichStagingDocumentRepository
.save(document);
enrichObjectId = enrichPayload.getId().toString();
} catch (Exception e) {
logger.error("EXCEPTION IN SAVETOENRICHDOCUMENT METHOD: " + e);
throw new AppException (e.getMessage(), e.getCause());
}
return enrichObjectId;
}
Here in the above method is the implementation when AppException extends the Exception class.
Now I need to change the save method according to runtime exception handling.
Question:
How can I change this method,without using try catch method?
If try catch is not there how the exception is get handled?

RuntimeExceptions don't have to be declared in the method signature, and if you want to remove the try/catch blocks as well - you can do it:
#Transactional(readOnly = false)
#Override
public String save(StagingDocument stagingData) {
String enrichObjectId = null;
EnrichDocument document = getEnrichDocument(stagingData);
EnrichDocument enrichPayload = enrichStagingDocumentRepository
.save(document);
enrichObjectId = enrichPayload.getId().toString();
return enrichObjectId;
}
When there's no try/catch - the exception doesn't get "handled" it is rather getting cascaded until either a higher level handles it or until the highest level exists the program (with the RuntimeException).

If you don't use a try-catch block, the original Exception would not be caught. If it is a RuntimeException, you will get no compilation errors as RuntimeExeption does not need to be caught. If that Exception occurs, it will simply be thrown from the save() method (it will be delegated).
If the original Exception is not a RuntimeException and you don't want to use a try-catch block, you may declare the save() method to throw that Exception but in this case it will obviously be not an instance of AppException but the original exception itself.
Btw, if you create an AppException, its cause should be e and not e.getCause(). If you pass e.getCause() as the cause of your AppException, then e itself will be lost. You might also want to add a custom error message and not use the original exception's message.
Summary: if you want your save() method to throw an instance of AppException if an Exception is encountered inside, you can't do that without a try-catch block, you have to catch it (the Exception encountered inside) and wrap it in a new AppException like you did.

Runtime exceptions need not be caught. If you are using AppException as a checked exception, still you need not put try/catch since you have already handled it using throws in the method signature. The method which is calling save() will have to handle the AppException.

Related

Is ValidationException a runtime exception or not?

Can anyone please give me information about it. I cant really uderstand the type of this Exception.
Thank you
public class ValidationException extends Exception{
public ValidationException(){
super("There was a problem when validating data");
}
public ValidationException(String message){
super(message);
}
public ValidationException(String message, Throwable throwable){
super(message, throwable);
}
public ValidationException(Throwable throwable){
super(throwable);
}
}
It is a "runtime exception" in the (fatuous) sense that it is an exception that occurs at runtime. But that is true for all Java exceptions ... apart from bugs in the compiler, etcetera.
It is not a subclass of RuntimeException. You have declared it as a subclass of Exception and Exception is not a subclass of RuntimeException. (In fact, the reverse is true: RuntimeException is a subclass of Exception!)
It is a checked exception because it is not a subclass of RuntimeException (or Error).
Since it is a checked exception, the Java rules about checked exceptions apply. For example, any method that throws or propagates1 your exception must declare that it throws this exception, or an exception that is a superclass of this exception.
1 - Technically, the JLS describes this as an abnormal termination of the method body with this exception as the abnormal termination reason.
The main difference between Exception, and RuntimeException is that we need to wrap a Exception in a try/catch block. A RuntimeException does not need to be caught, but it is just as lethal as an Exception.
public class Main{
public static void main(String[] args) {
Thread.currentThread().setUncaughtExceptionHandler(
new Thread.UncaughtExceptionHandler(){
#Override
public void uncaughtException(Thread t, Throwable e){
System.out.println("Uncaught Exception " + e);
}
});
try{
throwException();
}catch(Exception e){
System.out.println("Caught Exception " + e);
}
try{
throwRuntimeException();
}catch(Exception e){
System.out.println("Caught RuntimeException " + e);
}
//unchecked, no need to wrap int try/catch
throwRuntimeException();
}
public static void throwException() throws Exception {
throw new Exception();
}
public static void throwRuntimeException() {
throw new RuntimeException();
}
}
Take this example above. The output is this:
Caught Exception java.lang.Exception
Caught RuntimeException java.lang.RuntimeException
Uncaught Exception java.lang.RuntimeException
As you can tell, the call to throwRuntimeException() gets thrown, and since there is no try/catch block it has no idea how to handle it. This crashes the thread and since there is an UncaughtExceptionHandler it gets called.
Then there is also Error which I won't go into since I don't know much about it besides that JVM throws it. OutOfMemoryError is an example.

Do we need to throw the same exception in catch block which is already mentioned in method signature using throws declaration

I have a method in my Java App which throws SQLException. Is it necessary to throw the SQLException in the catch block so that the exception is thrown to the calling method where the exception is handled?
public void insert(Connection conn) throws SQLException
{
try {
// my code
} catch (SQLException s) {
throw s;
}
}
If you want to handle the exception yourself and then pass it to the calling method, then yes, you will need to re-throw it:
public void insert(Connection conn) throws SQLException {
try {
// Your code.
} catch (SQLException s) {
// Handle s.
throw s;
}
}
If you don't need to do anything with the exception and just want to pass it to the calling method then you can just omit the try-catch and if an exception is thrown the calling method will receive it:
public void insert(Connection conn) throws SQLException {
// Your code.
}
The error occur because you place your code inside a 'try-catch' block, if any exception will happen the catch block handle with it. not send to the calling method.
You can use the below function to thrown the exception to the calling method
public void insert(Connection conn) throws SQLException {
//code.
}
If you declare exception in throws clause of the method, then you can:
1) throw exception of declared type.
2) throw exception of subtype of declared type.
3) swallow the exception. (Not recommended as you have declared it in signature)
4) throw any other runtime exception.
Now coming to your example, It would be good to re-throw the exception so that the caller method knows that something wrong happened and take appropriate action (e.g. if a transaction is running on the Connection object then roll-back the transaction).

Is it possible to ignore an exception?

In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
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.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions. Checked exceptions 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.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
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.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}

java: can't rethrow exception: Unhandled exception type Exception

I'd like to catch an exception, log it, set a flag, and the rethrow the same exception
I have this code:
public Boolean doJobWithResult() {
boolean result = true;
final Feed feed = Feed.findById(feedId);
try {
feed.fetchContents();
} catch (Exception ex) {
result = false;
Logger.info("fetching feed(%d) failed", feedId);
throw ex;
}
return result;
}
But eclipse complains at throw ex, telling that "Unhandled exception type Exception", and suggests me to add a try-catch block around it.
In fact, I want the process calling this method to handle the exception, and not handle it myself... I just want to return true if everything goes ok, and log it if there's an exception
On the other hand, I can wrap the exception inside another exception, but I can't throw the same one..
any idea?
I think there are various things to mention here:
You either want doJobWithResult() to return true on success and false on failure, or return nothing on success and throw an exception on failure.
Both at the same time is not possible. In the first case, catch the Exception, log it and return false, in the second case change your signature to return void and throw an exception and handle it in the caller.
It's a Don't to catch an exception, log it and rethrow it. Why? Because a potential caller of your method does not know that you are already logging it, and migh log it as well.
Either throw an exception (in which case the caller has to deal with it) or catch it and handle it (log it).
Note that throwing Exception does not give the caller of your method any clue about what might potentially go wrong in your method, it's always better to throw more specific exceptions, or to wrap an exception in a user-defined one and rethrow it.
Moreover, if you throw Exception, a caller might be tempted to catch Exception without noticing that this will also catch every RuntimeException (since its derived from Exception), which might not be desired behavior.
Your doJobWithResult method needs to declare that it can throw Exception:
public Boolean doJobWithResult() {
becomes
public Boolean doJobWithResult() throws Exception {
You can throw the same exception if you add throws Exception to your method signature.
Otherwise you can throw a RuntimeException.
public Boolean doJobWithResult() {
boolean result = true;
final Feed feed = Feed.findById(feedId);
try {
feed.fetchContents();
} catch (Exception ex) {
result = false;
Logger.info("fetching feed(%d) failed", feedId);
throw new RuntimeException(ex);
}
return result;
}
In such a case, you won't need to indicate that public Boolean doJobWithResult() throws something but make sure you handle it properly later on (catch or expect your thread to stop... it's a RuntimeException afterall).
Since Exception is checked, an alternative to catching the Exception is to declare your method as throwing it:
public Boolean doJobWithResult() throws Exception {
// ...
}
If doJobWithResult doesn't have to handle the exception, then remove the catch block and add "throws Exception" to the method signature. The exception logging can be done in the class/method that have to deal with the Exception in a corresponding try/catch block.
There is no need to set the result as false in the catch block, as the value won't be returned(as we are throwing an exception).
Your method should also declare that it throws an exception and so the client will be forced to handle it.
Also consider using a more specific exception which will be thrown in this particular case.
Add throws Exception to your method. You also don't need to add result = false; in your catch block.
I think the way you handle this exception is really appropriate if any failure of feed.fetchContents() method cannot be recovered. (Idea is better to halt rather than continuing)
Apart from that I would suggest you to use more specific exception hierarchy.
And another thing I got from effective java book is if you write such a method you must document with #throw (in comments) with the reason.
You could throw an unchecked exception
Logger.info("fetching feed(%d) failed", feedId);
throw new RuntimeException(ex);
I spent the last hour looking for it since not even the Complete Reference book mentions this explicitly: unhandled throw ThrowableInstance works only with unchecked exceptions.. And only runtime exceptions are unchecked. By unhandled I mean something like this:
class ThrowDemo {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // re-throw the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
This example is taken verbatim from the Complete Reference book (9th edition).
The first throw statement i.e throw new NullPointerException("demo"); is handled by the following catch block, but the second throw statement i.e. throw e; is unhandled by the demoproc() method. Now this works here and the above code compiles successfully because NullPointerException is a runtime/ unchecked exception. If the e instance were a checked exception or even an Exception class instance then you'd get an error saying the exception e is unhandled and you'd either have to handle it within demoproc() or you'd have to explicitly declare that demoproc() throws an exception using throws in the method signature.

Exception handling : throw, throws and Throwable

Can any of you explain what the differences are between throw, throws and Throwable and when to use which?
throws : Used when writing methods, to declare that the method in question throws the specified (checked) exception.
As opposed to checked exceptions, runtime exceptions (NullPointerExceptions etc) may be thrown without having the method declare throws NullPointerException.
throw: Instruction to actually throw the exception. (Or more specifically, the Throwable).
The throw keyword is followed by a reference to a Throwable (usually an exception).
Example:
Throwable: A class which you must extend in order to create your own, custom, throwable.
Example:
Official exception-tutorial
throw: statement to throw object t where t instanceof java.lang.Throwable must be true.
throws: a method signature token to specify checked exceptions thrown by that method.
java.lang.Throwable: the parent type of all objects that can be thrown (and caught).
See here for a tutorial on using exceptions.
This really easy to understand.
The java.lang.Throwable:
The Throwable class is
the superclass of all errors and
exceptions in the Java language. Only
objects that are instances of this
class (or one of its subclasses) are
thrown by the Java Virtual Machine or
can be thrown by the Java
throw statement.
Similarly, only this class or one of
its subclasses can be the argument
type in a catch clause.
More
The key word throws is used in method declaration, this specify what kind of exception[Throwable class] we may expect from this method.
The key word throw is used to throw an object that is instance of class Throwable.
Lest see some example:
We create ourself an exception class
public class MyException super Exception {
}
The we create a method that create a object from our exception class and throws it using key word throw.
private void throwMeAException() throws MyException //We inform that this method throws an exception of MyException class
{
Exception e = new MyException (); //We create an exception
if(true) {
throw e; //We throw an exception
}
}
When we are going to use method throwMeAException(), we are forced to take care of it in specific way because we have the information that it throws something, in this case we have three options.
First option is using block try and catch to handle the exception:
private void catchException() {
try {
throwMeAException();
}
catch(MyException e) {
// Here we can serve only those exception that are instance of MyException
}
}
Second option is to pass the exception
private void passException() throws MyException {
throwMeAException(); // we call the method but as we throws same exception we don't need try catch block.
}
Third options is to catch and re-throw the exception
private void catchException() throws Exception {
try {
throwMeAException();
}
catch(Exception e) {
throw e;
}
}
Resuming, when You need to stop some action you can throw the Exception that will go back till is not server by some try-catch block. Wherever You use method that throws an exception You should handle it by try-catch block or add the declarations to your methods.
The exception of this rule are java.lang.RuntimeException those don't have to be declared. This is another story as the aspect of exception usage.
throw - It is used to throw an Exception.The throw statement requires a single argument : a throwable class object
throws - This is used to specifies that the method can throw exception
Throwable - This is the superclass of all errors and exceptions in the Java language. you can throw only objects that derive from the Throwable class. throwable contains a snapshot of the execution stack of its thread at the time it was created
Throw is used for throwing exception, throws (if I guessed correctly) is used to indicate that method can throw particular exception, and the Throwable class is the superclass of all errors and exceptions in the Java
How to Throw Exceptions
Throw :
is used to actually throw the exception, whereas throws is declarative for the method. They are not interchangeable.
throw new MyException("Exception!);
Throws:
This is to be used when you are not using the try catch statement in your code but you know that this particular class is capable of throwing so and so exception(only checked exceptions). In this you do not use try catch block but write using the throw clause at appropriate point in your code and the exception is thrown to the caller of the method and is handled by it. Also the throws keyword is used when the function may throw a checked exception.
public void myMethod(int param) throws MyException
There are 2 main types of Exceptions:
Runtime Exceptions(unchecked): eg. NullPointerException, ClassCastException,.. Checked Exceptions: eg. FileNotFoundException, CloneNotSupportedException, ..
Runtime Exceptions are exceptions that occur at runtime and the developer should not try to catch it or stop it. You only write code to avoid them or issue a command throw, when the error criteria is met. We use throw inside the method body.
public Rational(int num, int denom){
if(denom <= 0) {
throw new IllegalArgumentException("Denominator must be positive");
}
this.num=num;
this.denom=denom;
}
However for Checked Exceptions, the JVM expects you to handle it and will give compiler error if not handled so you declare that it throws that type of exception as seen below in the clone() method.
Class Employee{
public Employee clone() throws CloneNotSupportedException{
Employee copy = (Employee)super.clone();
copy.hireDate = (Date)hireDate.clone();
return copy;
}
}
Same answer as above but with copy-paste pleasure:
public class GsonBuilderHelper {
// THROWS: method throws the specified (checked) exception
public static Object registerAndRun(String json) throws Exception {
// registering of the NaturalDeserializer
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Object.class, new NaturalDeserializer());
Gson gson = gsonBuilder.create();
Object natural = null;
try {
// calling the NaturalDeserializer
natural = gson.fromJson(json, Object.class);
} catch (Exception e) {
// json formatting exception mainly
Log.d("GsonBuilderHelper", "registerAndRun(json) error: " + e.toString());
throw new Exception(e); // <---- THROW: instance of class Throwable.
}
return natural;
}
}

Categories