Skip to main content

Function that does not return normally

Posted by forax on August 26, 2006 at 8:04 AM PDT

It's a recurring problem, you have a code that always generates an exception

   public void throwIOException(int code) throws IOException {
     throw new IOException(IO.getMessage(code));
   }
 

and you use it in a method like this :
   public int read() throws IOException {
     int value=readAByte()
     if (value!=-1)
       return value;
     throwIOException(IO.errorCode);
   }
 

Because there is no way to say to the compiler something like
"hey, the method throwIOEXception doesn't return",
the compiler emit an error
because the method read() could return without a value.

In the now famous closure proposal, there is a small section titled
"The type of null" that i understand like this:
if you use null as return type,
you can indicate that the method never return.

   public null throwIOException(int code) throws IOException {
     throw new IOException(getMessage(code));
   }
 

Pretty cool !

update: see Function that does not return normally II (the return) for the part2 of this entry.

Related Topics >>