Exception Handling:Throw, Throws and Throwable

Exception handling : throw, throws and Throwable

  • 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:

Sample Image



  • Throwable: A class which you must extend in order to create your own, custom, throwable.

Example:

Sample Image



  • Official exception-tutorial

Difference between Throw and Throws in Java- Clarification

Throw actually returns the exception whereas throws is a sign to the compiler, that this method could return an exception.

In your code above the exception ArithmeticException will be created and returned, if the grade is lower than 5, which is the case in your second call of QAExperience.
As the calling method called the method, which returned the exception, is not insede a catch block it will also just stop its execution and return to the main method. As the main method also does not catch the exception it will just like the others stop its execution and return the exception. This is the reason, why t.checkThrowsExp will not be executed.

Difference between throw and throws in Java?

  1. throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.

  2. If we see syntax wise then throw is followed by an instance variable and throws is followed by exception class names.

  3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).

For example

throw

throw new Exception("You have some exception")
throw new IOException("Connection failed!!")

throws

public int myMethod() throws IOException, ArithmeticException, NullPointerException {}

  1. You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.

  2. checked exceptions can not be propagated with throw only because it is explicitly used to throw an particular exception. checked exception can be propagated with throws.

Exception propagation: An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.
what is exception propagation?

What is the importance of throw keyword when already throws and try-catch block are available in JAVA?

The meaning is there in the words only.

Keyword throw is a action word, for example throw new Exception() means the code is throwing an Exception, meaning if the execution control reaches this code, exception will be thrown. This is internal to a method.

Keyword throws is a declaration to the users of the method (code calling the method) that the method can throw an exception.

try-catch is an mechanism to try a code which can throw an exception and then catch the same if thrown.

Should I avoid throwing Throwable when dealing with a method that throws Throwable?

No, it is not okay to throw Throwable. Errors and unchecked exceptions are not supposed to be caught; Errors are serious or fatal system problems, while unchecked exceptions (usually) expose programmer mistakes. Declaring a signature with throws Throwable forces callers to catch, and allows them to suppress, things which shouldn't be caught or suppressed.

If at all possible, you should fix the ProceedingJoinPoint.proceed() method's signature, but if you don't have control over that class, your own code should wrap it in a more reasonable exception.

How to wrap it depends on what you expect of callers of your code. If any Throwable is likely to be a condition that no one can possibly do anything to correct or address, you might as well wrap it in an unchecked RuntimeException:

try {
return joinPoint.proceed();
} catch (Throwable t) {
throw new RuntimeException(t);
} finally {
//some more code here
}

If you want to make sure callers handle all Throwables gracefully, you should create your own application-specific exception class:

try {
return joinPoint.proceed();
} catch (Throwable t) {
throw new JoinPointException(t);
} finally {
//some more code here
}

The exception class is simply:

public class JoinPointException
extends Exception {
private static final long serialVersionUID = 1;

public JoinPointException(Throwable cause) {
super(cause);
}

public JoinPointException(String message,
Throwable cause) {
super(message, cause);
}
}

Is throws Throwable good practice

You should not throw Throwable. Here's why.

Throwable is the top of the hierarchy of things that can be thrown and is made up of Exceptions and Errors. Since Errors by definition arise from unsalvagable conditions, it is pointless to include them in your method declaration. That leaves just Exception.

You should declare your method with throws Exception instead.



Note that the narrower the range of throws the better.

Declaring your method to be throws Exception is ok if your method doesn't generate the exceptions, but instead calls other code that is declared as throws Exception and you want exceptions to percolate up the call stack.

If your method is the generating the exception, then declare a narrower range, eg throws IOException, MyProcessingException, etc

What is the difference between throws Throwable and throws Exception

Exceptions are for errors in the program logic. Error are used by the JVM to signal that something is wrong with the environment such as an OutOfMemoryError or IncompatibleClassChangeError. ThreadDeath is used to kill Threads. Throwable is a super class over all of these.

In normal program logic, you should never throw nor catch Throwables or Errors. The main reason I can think of for catching a Errors is this: You are using your own class loading system and want to isolate broken plugins.

The JavaDoc for ThreadDeath for example says:

An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.

what is the difference between throwing a new exception within a body of a method and throwing the exception in the header of the method

public abstract String test(String value) throw new testException;

does not make sense. The closest thing you can do is write

public abstract String test(String value) throws testException;

which indicates that test is a method that could throw a testException. If testException is not a RuntimeException, then it must be declared like that. But adding throws testException to the method signature only says that the method could throw that exception, it doesn't actually do the throwing.



Related Topics



Leave a reply



Submit