Throwing Java Exceptions - java

When a method throws and exception, do we need to have a try block inside the method?
For example,
public void foo() throws SomeException{
try{
// content of method
}
}
Is the try block required? Or, is the method able to throw a SomeException without it :
public void foo() throws SomeException{
// content of method
}
This is the case when we are not explicitly throwing a SomeException with throw.

If SomeException is a checked exception you have to either
Use a try{}catch block or
Declare that your method throws it.
You do not have to do both, either example you show in your question works just fine.
The difference is that with the try clause you handle the SomeException yourself, whereas by declaring that your own method throws it you delegate the responsability of handling the SomeException to the calling method.

When a method throws an exception it passes responsibility to handle exception to its caller.
So you don't need to handle exception if you throw it in your signature. Like as follows.
public void foo(){
try{
// content of method
}
}
but if you write it this way.
public void foo() throws SomeException{
}
you will call your method like as follows.
try{
foo();
}

You don't need a try block.
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}
As long as you declare it in your signature, you're prefectly fine. The caller of your method has to handle the exception, not you. So a caller might do:
try {
foo();
} catch (SomeException e) {
// handle exception
}
Or he might pass it further along by himself.

The most problematic case you'll regularly encounter is calling a method that declares a checked exception. In the great majority of real-life cases it is not appropriate to handle that exception at the spot, but let it propagate upwards. Unfortunately, Java makes you redeclare this same exception all the way up, which creates clutter, exposes implementation details, and often also breaks the contracts of existing methods.
In such a case the way to proceed is to wrap and rethrow:
catch (RuntimeException e) {throw e;} catch (Exception e) {throw new RuntimeException(e);}

1. If the method that we are calling from a program throws an Exception, then we need to usetry/catch around the method invocation.
2. Suppose we are writing a method that throws an exception, then we need to throw new Exception object from withing the method.
3. An exception is an object of type Exception. We have Checked Exception, and Unchecked Exception (Runtime Exception).

you don't essentially need to have a try block in it
public void foo() throws SomeException {
// do some stuff
// you decide to throw the exception by yourself:
if (throwAnException) throw new SomeException();
// or you call a method that throws SomeExpection:
methodThatCanThrowSomeException();
// do more stuff
}

Related

Throw Exception catch childException... why not?

Say I have a method doSomething() which throws a checked exception, then in my main method I enclose doSomething() in a try catch.
Question:
Say I throws Exception in doSomething(). Why can't I catch (ChildException e) in my main method?
I know I can't and that I must catch Exception, but I don't understand why.
ChildException extends Exception.
If I throws ChildException and catch Exceptionthen there's no problem understandably so. Why not the other way round?
You can catch ChildException in your main method, but because the method you call is defined as throws Exception, you will also have to catch Exception, because the compiler does not know that doSomething is only throwing ChildException. If that is what you want, then you should define doSomething as throws ChildException instead.
For example with your current setup you could do:
try {
doSomething();
} catch (ChildException e) {
// handle child exception
} catch (Exception e) {
// handle other exceptions
}
As commented by MC Emperor, order of catch blocks is important, if you'd reverse the order and catch Exception first, then that block will also handle ChildException, and the ChildException-specific block will not be used.
Alternatively, change doSomething():
public void doSomething throws ChildException {
// ...
}
If your code throws ChildException child, you can catch it with Exception parent , because ChildException extends Exception, so child is assignable to parent i.e. you can write something like
Exception parent = child;
But if your code says you are throwing an Exception, the compiler takes you at face value and assumes that the exception type thrown by your method can be of any subclass of Exception or of the class Exception itself.
For example , your method may throw another ChildException2. So, in that case it is not assignable to ChildException in the catch clause of main method. The ChildException2 is neither handled nor declared.
So, the compiler doesn't allow you to continue with just catching the ChildException and asks you to either catch the type Exception or declare it.

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);
}

Catching Exceptions and Rethrowing

I'm new to the Java scene but currently working on an assigned assessment. I'm wondering if there is a way to catch an exception inside a class function and throw another exception so the function that called the class function doesn't need to know about the first exception thrown.
For example
public void foo() throws MasterException {
try {
int a = bar();
} catch (MasterException e) {
//do stuff
}
}
public void bar() throws MasterException, MinorException {
try {
int a = 1;
} catch (MinorException e) {
throw new MasterException();
}
}
I hope this example explains what I'm trying to achieve. Basically I want the calling function not to know about MinorException.
Remove , MinorException from the declaration of bar and you are done.
I would also do:
throw new MasterException(e);
If MasterException had a constructor that supported it (its standard it does, the Exception class do).
Absolutely. You want to change this line:
public void bar() throws MasterException, MinorException
to this:
public void bar() throws MasterException
Everything else should work exactly how you've written it.
Just remove the MinorException from throws clause of bar().
I would remove MasterException from foo() as you are catching it and as the other answers say, MinorException from bar().
Additionally, in case MasterException or MinorException is a subclass of RuntimeException, you do not need to declare it. See e.g. http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Remove throws MasterException from the declaration of method foo(), the reason is clear that the MasterException has been ready catched SO would not get occurred anyway.
Remove , MinorException from the declaration of method bar().

Calling a method which throws FileNotFoundException

I'm pretty sure this is an easy one but I could not find a straight forward answer. How do I call a method with a throws FileNotFoundException?
Here's my method:
private static void fallingBlocks() throws FileNotFoundException
You call it, and either declare that your method throws it too, or catch it:
public void foo() throws FileNotFoundException // Or e.g. throws IOException
{
// Do stuff
fallingBlocks();
}
Or:
public void foo()
{
// Do stuff
try
{
fallingBlocks();
}
catch (FileNotFoundException e)
{
// Handle the exception
}
}
See section 11.2 of the Java Language Specification or the Java Tutorial on Exceptions for more details.
You just call it as you would call any other method, and make sure that you either
catch and handle FileNotFoundException in the calling method;
make sure that the calling method has FileNotFoundException or a superclass thereof on its throws list.
You simply catch the Exception or rethrow it. Read about exceptions.
Not sure if I get your question, just call the method:
try {
fallingBlocks();
} catch (FileNotFoundException e) {
/* handle */
}
Isn't it like calling a normal method. The only difference is you have to handle the exception either by surrounding it in try..catch or by throwing the same exception from the caller method.
try {
// --- some logic
fallingBlocks();
// --- some other logic
} catch (FileNotFoundException e) {
// --- exception handling
}
or
public void myMethod() throws FileNotFoundException {
// --- some logic
fallingBlocks();
// --- some other logic
}
You call it like any other method too. However the method might fail. In this case the method throws the exception. This exception should be caught with a try-catch statement as it interrupts your program flow.

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