Return only if no Exception is thrown - java

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

Related

Function's return type can be Exception when it throws Exception

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 + "'!");
}
}

what is the effect that explicits the "throw exception" in the method signature

--the effects of case 1 and 2 are the same, why need to add the exception declaration in method signature?
//case 1
public void doSomething() throws Exception {
//do Something
}
public void Caller() {
try {
doSomething();
} catch (Exception e) {
//handle the exception
}
}
//case 2
public void doSomething() {
//do Something
}
public void Caller() {
try {
doSomething();
} catch (Exception e) {
//handle the exception
}
}
reference:
what is the use of throws Exception
The throws declaration is used to declare which checked exceptions your method throws.
For instance, if I write this code:
public void doSomething() throws SQLException {
}
any code that calls this method must have a try/catch block for SQLException, Exception, or Throwable... or it can have its own throws declaration for one of those 3.
In this case, there is no difference, except that you're alerting the compiler to an exception that you're not going to be throwing.
It's also a bad idea to catch throw "Exception" - in both cases, you want to deal a particular exception that has a particular meaning. When you're catching, the only reason to use a try block is if you expect a particular exception, so you should catch that one. This way, if some unexpected exception comes up, you don't try to handle it the wrong way. (instead, your program fails, and you know there's a condition you have to deal with) When you're throwing, you want to throw a particular exception, either one you make up, or a standard one that has a known meaning, so the calling function knows what to deal with. For example, if your doSomething might throw an ArrayIndexNotFoundException if the widgets are not frobnicated, you might want to catch the ArrayIndexNotFoundException and throw a WidgetNotFrobnicatedException. Any time you throw an exception, your javadoc should specify exactly what circumstances will trigger that issue, so the user of your code has a chance to address this possible failure.
(there is one circumstance when I can see catching Exception, and that's if you want to fade to some graceful halt if things go wrong unexpectedly - in that case, in your catch block you'd log the issue, possibly alert a developer, and throw up some sort of "Sorry, error number 3542 has occurred, please restart the program" message.)
If your doSomething method, has the chance to throw an exception and you don't want to catch it, you should add this throws Exception on the method.
Unless it's an exception that you want to handle immediately in that method, it's good practice to use throws [specific Exception] so that the exception can be handled further up in the code.
It's somewhat commonplace to have a generic Throwable catch at the top that "gracefully crashes" in case something goes wrong.

Is it necessary to use "throws" whenever we use "throw"?

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

libgdx catches all exceptions, only presents RuntimeException instead of original one

I'm trying to debug a libgdx application... Obviously, I'm producing a NullPointerException at some point, but libgdx has a huge try-catch statement that catches my original exception:
public void run () {
graphics.setVSync(graphics.config.vSyncEnabled);
try {
LwjglApplication.this.mainLoop();
} catch (Throwable t) {
if (audio != null) audio.dispose();
if (t instanceof RuntimeException)
throw (RuntimeException)t;
else
throw new GdxRuntimeException(t);
}
}
So the debugger stops in the catch statement where the (Gdx)RuntimeException is thrown. I know that t contains the original exception, but I can't really tell where it came from. Is there any way to break at the line that produces that exception?
Untested with libgdx but in similar systems you might be able to do…
try {
foo.run ()
} catch (RuntimeException t) {
System.err.println ("** Caught a runtime exception.");
t.printStackTrace();
Throwable tCause = t;
while (tCause = tCause.getCause()) {
System.err.println("→ caused by:");
t.getCause.printStackTrace ();
}
}
It appears that GdxException.GdxException (Throwable) should call super (t) which in turn should “stash” t in the property for the getCause accessor.
PS: Have you tried running a static analyzer like FindBugs to locate potential NPE's?
How about inspecting the stacktrace and inserting a breakpoint where the NullPointerException is generated?
This is the solution that worked: Add the exception that is shown in t to the list of exceptions that should always trigger the debugger, even when being catched:
Break when exception is thrown
Thanks for the help though :)

How to make a try-catch block that keeps on calling a method on an object until there are no more exceptions to catch

Basically iterating through a list and,
- Invoke method on first object
- Catch the first exception (if any); if there are no more exceptions to catch, return normally. Otherwise, keep on invoking method until all exceptions are caught.
- Move on to next object.
I can iterate through each object, invoke the method, and catch one exception but I do not know how to continuously invoke the method on it and keep on catching exceptions.
This is similar to the other answers, but without the flag, which seems like clutter to me. I don't really understand the question though, so I'm just throwing it out there in case it is useful.
for (Item item : items) {
while (true) {
try {
item.doSomething();
break;
} catch (MyException ex) {
log.warn("Something failed.", ex);
}
}
}
This approach hinges on the operation of the unlabeled break statement, which completes abruptly and then exits the enclosing while statement normally.
Based on subsequent comments, I think there is some confusion about what it means when there are multiple exceptions declared to be thrown by a method.
Each invocation of a method can be terminated by just one exception being thrown. You can't somehow resume invocation where it left off, and handle subsequent exceptions.
So, if a method throws multiple exceptions, catch a common ancestor, and move on. For example, if a method throws java.io.EOFException or java.nio.channels.ClosedChannelException, you could simply catch java.io.IOException since it is a common ancestor. (You could also catch java.lang.Exception or java.lang.Throwable for the same reason.) Invoking the method again under the same conditions won't get you any further.
If you want to attempt to invoke the method on each object, even if some fail, use this:
for (Item item : items) {
try {
item.doSomething();
} catch (Exception ex) { /* This could be any common ancestor. */
log.warn("Something failed.", ex);
}
}
If you're talking about dealing with a single method call that will throw more than one exception, it can't be done -- no matter how many times you call the method, it will keep on throwing the first exception. You can't go back into the method and keep running from there; after throwing one exception, it's all over.
But if you're talking about a method that sometimes throws exceptions and sometimes doesn't, try something like this:
boolean thrown = false;
do {
try {
thrown = false;
method();
}
catch (Exception e) {
thrown = true;
// Handle as you like
}
} (while thrown);
This is what I understand.
You have an object's method which may throw a number of exceptions.
What you want to do is to catch them all and continue with the next object in the list.
Is that correct?
So, that would be:
for( YourObject o : yourList ) {
try {
o.thatMethod();//invoke that risky method
} catch( SomeExceptionClass sec ) {
// Do something with that exception
} catch( SomeOtherExceptionClass soec ) {
// Do something with that exception
} catch( YetAnotherxceptionClass yaec ) {
// Do something with that exception
} catch( OtherUnRelatedException oue ) {
// Do something with that exception
}
}
When you do this, if the invocation of thatMethod() throws an exception and that exception is listed in the catch section, the execution flow will jump to that exception and after it will continue to the normal flow ( which is the for loop and will continue with the next object )
I hope this is what to need. For more information read: The catch block in the Java Tutorial section Essential classes
I'm assuming that you are trying to performs some kind of validation to the items in a list, where the validation errors are reported by throwing exceptions. I'm also assuming that you are trying to collect all of the validation errors.
The simple answer is that this problem cannot be solved using this approach. To understand why, take a look at this:
boolean exceptionCaught = false;
do {
try {
item.doSomething();
} catch (MyException e) {
exceptionCaught = true;
}
} while (exceptionCaught);
This fails because each time you call item.doSomething() it is going to throw an exception at exactly the same place. The net result is an infinite loop.
The best you can do with this approach is to capture the first exception for each item in the list.
So how can you achieve what you are trying to achieve? The answer is that you have to change the validation code to use some other way to report errors than throwing exceptions. For example, you could change:
class Item {
...
void validate() {
if (noHat) {
throw new MyException("bad hat");
}
if (noPants) {
throw new MyException("world-wide pants");
}
}
}
to something like this:
class Item {
...
void isValid(List<MyException> errors) {
boolean ok = true;
if (noHat) {
errors.add(new MyException("bad hat"));
ok = false;
}
if (noPants) {
errors.add(new MyException("world-wide pants"));
ok = false;
}
return ok;
}
}
Messy huh! You could sugar this in various ways, but this style of error reporting is always going to be more complicated. But I don't think there is a practical way to avoid the messiness AND capture ALL of the validation errors.

Categories

Resources