I am interested to know best practice to use throw new Exception() and new Exception(). In case of using new Exception(), I have seen that code moves to next statement instead of throwing exception.
But I am told that we should use new Exception() to throw RuntimeException.
Can anyone throw some light on this ?
new Exception() means create an instance (same as creating new Integer(...))
but no exception will happen until you throw it...
Consider following snippet:
public static void main(String[] args) throws Exception {
foo(1);
foo2(1);
}
private static void foo2(final int number) throws Exception {
Exception ex;
if (number < 0) {
ex = new Exception("No negative number please!");
// throw ex; //nothing happens until you throw it
}
}
private static void foo(final int number) throws Exception {
if (number < 0) {
throw new Exception("No negative number please!");
}
}
the method foo() will THROW an exception if the parameter is negative but
the method foo2() will create an instance of exception if the parameter is negative
Exception e = new Exception ();
Just creates a new Exception, which you could later throw. Using
throw e;
Whereas
throw new Exception()
Creates and throws the exception in one line
To create and throw a runtime exception
throw new RuntimeException()
new Exception() means you are creating a new instance of Exception type. Which means you are just instantiating an object similar to others like new String("abc"). You would do this when you are about to throw an exception of type Exception in next few lines of code execution.
While when you say throw new Exception() this means you are saying move the program control to caller and don't execute the further statements after this throw statement.
You would do this in a situation where you find that there is no way to move ahead and execute further and hence let caller know that i can't handle this case and if you know how to handle this case, please do so.
There is no best practice as such as you are comparing oranges with apples. But remember when throwing an exception, you always throw a meaningful exception like IO has where if file is not present it throws FileNotFoundException instead of its parent IOException.
Related
Let's say I have a function
private RuntimeException foo() {
return new RuntimeException();
}
and exception there is not thrown and it can be processed like
throw foo();
or return value can be assigned to a variable
RuntimeException e = foo();
But the function can be changed to
private RuntimeException foo() {
throw new RuntimeException();
}
and it still compiles and can be used like in previous examples or can just be called like foo(); and Exception will be thrown.
But why is it possible to specify RuntimeException as a return type of a method that doesn't return it but throws it instead. Is there any connection between throw and return behavior in this case?
I've noticed that having Exception (or more generally Throwable) return type ensures that it will be thrown/returned in every decision branch like if/else statements. But is there any more practical usage or recommended of this?
Since throw will make the execution of the method stop immediately and control is passed back to the caller, it doesn't matter what your method returns. No matter what type you return, that type will not be returned, because you are throwing an exception (which indicates something wrong happened) on the first line.
The compiler allows this because throwing an exception means something wrong happened, like the arguments are invalid, or the argument is null, and so on. In such error conditions, the compiler does not expect the method to return a value normally. It makes sense because obviously when something wrong happens, the method can't compute whatever it is that it was going to compute.
So the phrase "all code paths must return a value" should really say "all code paths must return a value or throw a Throwable".
There is no relation between what a method returns and what it can throw.
and there are use cases where a method may both return and throw an exception.
consider the following scenario: a method that is called to produce an application-specific exception:
public Exception produceException(User u) {
if (u.id == null) return new UserNotFoundException();
if (u.name == null) return new UserDidNotCompleteRegistrationException();
if (u.email == null) return new UserDidNotVerifyEmailException();
}
now guess what will happen if the argument itself is null? and the method does not even declares a throws clause...
now, regarding having Exception as return value for the sake of ensuring that an exception is returned at every branch is just bad design. return value is not the mechanism to be used for throwing exception. if you surround the entire method body with try-catch you will catch all exceptions from all branches.
why is it possible to specify RuntimeException as a return type of a method that doesn't return it but throws it instead. Is there any connection between throw and return behavior in this case?
It's possible to specify any type as a return type of any method. There is no connection between return and throw behavior.
I've noticed that having Exception (or more generally Throwable) return type ensures that it will be thrown/returned in every decision branch like if/else statements
No, that's not the case. There is no way to "ensure [an Exception] will be thrown in every decision branch". The only thing you can do is to state "this method may throw an Exception by using the throws keyword:
public void mightThrowException() throws Exception {...}
but there's no guarantee that any exception will be thrown at all.
BTW, there are two types of exceptions: checked and unchecked. Unchecked exceptions are subclasses of RuntimeException; those do not need to be declared for your method. Checked exceptions do, so
public void throwsIoException() {
throw new IOException();
}
is illegal because IOException is a checked exception that needs to be declared with throws.
You mixed something up with your example. Because when throwing an exception in a method the return type is not really considered, so instead of declaring the method like in your example. you could also declare it like the following:
public void foo(){
throw new RuntimeException();
}
or:
public MyComplexType foo2(){
throw new RuntimeException();
}
The result is simply the same: An exception is thrown. The calling code just will look differently e.g:
foo(); // throws RuntimeException
myOtherComputation(); // is never reached
or
MyComplexType type = foo2(); // throws RuntimeException
type.doSomething(); // is never reached
This behaviour can be useful when using for example a switch statement in a method but throwing an error when entering the default branch:
public String foo(String string){
switch(string){
case "foo":
return "bar";
case "bar":
return "foo";
default:
throw new UnsupportedOperationException("Unknown string: '" + string + "'!");
}
}
Is an exception object created when a catch statement is implemented?
For example, catch (ArithmeticException someObject)
Does this object not have to explicitly be created as an instance?
There are two things creating Instance of the Exception the second throwing the Exception
creating an Instance of The Exception looks like creating any instance of Class for example NullPointerException npe = new NullPointerException(); at this moment we didn't do any thing more than creating an instance, some times we didn't create the instance of Exception by ourselves as we will see
Throwing Exception after creating instance of Exception class we throw it, you can throw the Exception by yourself or the JVM will do
try
{
int a = 10/0;
}catch(ArithmeticException a)
{
RuntimeException exception = new RuntimeException("a very bad error occured", a);
throw exception;
}
when Java tried to compute 10/0 it encounter an arithmetic error so the JVM creates an instance of class ArithmeticException and throws this created instance which you catch it in your catch clause, where we create an instance of class RuntimeException it's just an object and then throw it using throw
You are creating an object. But you aren't creating an instance of it.
The Exception object instance is created when someone throws it.
try {
Foo foo = null;
foo.dofoo();
} catch(NullPointerException e) {
// ...
}
In this particular case, the JVM created the NullPointerException object instance that you are handling in the catch block.
In few words imagine that in some part of the JVM there's something like:
if (obj == null) {
throw new NullPointerException();
}
Do not take the previous code sample serious. It's an exemplification of Exception throwing.
I'm implementing a fixed sized Queue in java which uses a constant size ArrayList as underlying container, where my front() method is supposed to return front element of Queue .
public T front(){
try{
if(isEmpty())
throw new Exception("Queue is Empty- can't return Front element.");
return arrayList.get(frontIndex);
}catch (Exception e){
System.out.println(e);
}
}
By coding in above way , I want front() to return a value only if no Exception is thrown ,however as expected compiler show me "Missing return statement." So , is there any way I can make the function return only if no Exception is thrown.
Since you are catching the exception in the code the compiler shows that missing return statement error.
You can implement the function Like this :
public T front() throws Exception {
if(isEmpty()) {
throw new Exception("Queue is Empty- can't return Front element.");
}
return arrayList.get(frontIndex);
}
and finally handle the exception at calling function/client
I want front() to return a value only if no Exception is thrown
Rhetorical question: What do you want to return if an Exception is thrown?
Here is the problem. You have declared front() as returning something (an instance of T). That means that there are two relevant ways1 to terminate a call to front():
It can terminate normally by returning something that conforms to the type T.
It can terminate abnormally by throwing an unchecked exception.
You can't return "nothing", because front() has to return a value.
You can't throw a checked exception (like Exception) because front() is not declared as throwing any exceptions.
So what can you do?
You can change the method signature so that SomeException is thrown, where SomeException descends from Exception. (Throwing Exception is a really bad idea ...)
You can change throw new Exception to throw new SomeException, where SomeException is descended from RuntimeException.
You can return null assuming that T is a reference type. (It will be if T is a type parameter.)
1 - Actually, there are a couple of other ways, but they are not useful in this context. For example, you could call System.exit(int) and terminate the JVM. (And there are ways of structuring the code so that you don't need a (redundant) return or throw following the exit call. Hint: infinite loops don't need to return.)
Why do you use the exception at all if you are catching it afterwards? You have to either return T or throw an exception. But the method doesn't throw an exception since you are catching it. Is it not easier to do just that:
public T front() throws SomeException{ // if SomeException is checked you need to declare it
if(isEmpty())
throw new SomeException("Queue is Empty- can't return Front element.");
return arrayList.get(frontIndex);
}
You should also use a more specific exception, not Exception.
this "example" shows a possibility when u can throw an exception and return value
private boolean throwExReturnValue() throws NullPointerException {
try {
throw new NullPointerException("HAHA");
}
finally {
return true;
}
}
private void ExceptionHanler() {
boolean myEx;
try {
myEx = throwExReturnValue();
/** code here will still execute & myEx will have value = true */
} catch (Exception ex) {
/** will execute or not (depending on VM) even we throwed an exception */
}
/** code will still execute */
}
EDIT:
i tried this with two different VM and to my surprise one is throwing Exception second is skipping the catch block and execute code so it's depending on VM implementation
This question already has answers here:
Exception handling : throw, throws and Throwable
(8 answers)
Closed 8 years ago.
Can any one clearly state the difference between throw and throws in Java exception handling with an example? I have tried googling but couldn't arrive at a conclusion. Pls help
throws clause is used to declare an exception and throw keyword is used to throw an exception explicitly.
If we see syntax wise then throw is followed by an instance variable and throws is followed by exception class names.
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 {}
You cannot declare multiple exceptions with throw. You can declare multiple exception e.g. public void method()throws IOException,SQLException.
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?
throw use for throwing actual Exception and throws declare at method it might throws Exception.
public int findMax(int[] array) throws Exception{
if(array==null)
throw new NullPointerException(...);
...
}
public void someMethod(List<Foo> someList) throws SomeException {
if (someList.isEmpty()) throw new SomeException();
}
Assuming that the Exception we are throwing is checked, is it compulsory to add throws in a method declaration whenever we use throw inside the method?
Any checked exception (e.g., one which does not extend RuntimeException) that might escape a method needs to be declared in the method signature. For example:
public static void mightThrow(String s) throws NumberFormatException {
// ...
int x = Integer.parseInt(s);
// ...
}
Even though we do not throw any exceptions directly, Integer.parseInt() might throw a checked NumberFormatException. Since we call that method, and we do not catch the potential exception, then our method must also declare the exeception in its throws signature.
This does not necessarily mean that every method that throws (or might throw) a checked exception must declare throws in its signature. If the thrown exception is always caught within that method, it need not be added to the signature. For example:
public static Integer tryParseInteger(final String s) {
try {
return Integer.parseInt(s);
}
catch (NumberFormatException ignored) {
return null;
}
}
In this example, we will always catch any NumberFormatException that might be thrown by Integer.parseInt() and prevent it from bubbling up the stack, so we do not need to declare it in our tryParseInteger() method.
Unchecked exceptions never need to be declared:
public static void unsupported() {
throw new UnsupportedOperationException(
"The specified operation is not supported."
);
}
Here, because UnsupportedOperationException derives from the unchecked RuntimeException, it does not need to be declared.
No, since you may want to throw a exception but handle it in the same place, aka method
The Throws simply let javac know that this method might cause this kind of exception. It is not always necessary. It's useful when you know that a specific method can throw some sort of exception.
Generally speaking, Java is exception-strict, so you have to specific what types of exceptions a method throws. Note that you can use inheritance to simplify your methods' signatures. E.g., you can declare your method as throws IOException, and within its implementation throw any type of IOException you want such as FileNotFoundExeption, InteruptedIOException, etc.
One exception (no pun intended) to this rule are RuntimeExceptions (such as OutOfMemoryError or UnsupportedOperationException) which can be thrown without having to declare them.
Differences:
1) You can declare multiple exception thrown by method in throws keyword by separating them in common e.g. throws IOException, ArrayIndexBoundException etc, while you can only throw one instance of exception using throw keyword e.g. throw new IOException("not able to open connection").
2) throws keyword gives a method flexibility of throwing an Exception rather than handling it. with throws keyword in method
signature a method suggesting its caller to prepare for Exception declared in throws clause, specially in case of checked Exception and provide sufficient handling of them. On the other hand throw keyword transfer control of execution to caller by throwing an instance of Exception. throw keyword can also be used in place of return as shown in below example:
private static boolean shutdown() {
throw new UnsupportedOperationException("Not yet implemented");
}
as in below method shutdown should return boolean but having throw in place compiler understand that this method will always throw exception .
3) throws keyword cannot be used anywhere exception method signature while throw keyword can be used inside method or static initializer block provided sufficient exception handling as shown in example.
static{
try {
throw new Exception("Not able to initialized");
} catch (Exception ex) {
Logger.getLogger(ExceptionTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
4) throw keyword can also be used to break a switch statement without using break keyword.
int number = 5;
switch(number){
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}