mjk8ball / exceptions4c

Automatically exported from code.google.com/p/exceptions4c
0 stars 0 forks source link

Is there a way to handle a "return" in the middle of a try block? #20

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
or if you do so, all hell break loose?

Original issue reported on code.google.com by luciot...@gmail.com on 14 Jul 2014 at 1:08

GoogleCodeExporter commented 9 years ago
Nope, there's no way to do that. You cannot `return`, `goto` or `break` out of 
a `try`, `catch`, or `finally` block.

You can do it in Java, but then the semantics of the `finally` block make the 
control flow in unexpected ways. Consider the next Java class:

    public class Foo{
        public static final int ERROR_NULL = -1;
        public static final int ERROR_EMPTY = -10;
        public static final int ERROR_FORMAT = -100;
        public static int bar(String number){
            Integer result = null;
            try{
                if( number.isEmpty() ) return(ERROR_EMPTY);
                try{
                    return( result = Integer.parseInt(number) );
                }catch(NumberFormatException error){
                    return(ERROR_FORMAT);
                }finally{
                    if(result < -100) return(-result);
                }
            }catch(NullPointerException error){
                return(ERROR_NULL);
            }
        }
    }

It's a small class, yet the results of `Foo.bar` are not so obvious, are they?

    Foo.bar("31416") => 31416
    Foo.bar("-42")   => -42
    Foo.bar("-256")  => 256
    Foo.bar(null)    => ERROR_NULL
    Foo.bar("")      => ERROR_EMPTY
    Foo.bar("ABC")   => ERROR_NULL

I don't mean that exceptions4c does not support returning in the middle of a 
`try` block *by design*. In fact, it is a *technical limitation*. I'm just 
saying that trying to overcome it may not be worthwhile. I hope I convinced you 
;)

Original comment by guillermocalvo on 16 Jul 2014 at 6:42