Question

I have written a class in which i am trying to throw a runtime exception. The code is as follows

public class ExceptionTest 

{

    public static void ReadFile() throws RuntimeException, FileNotFoundException{
    try{

    BufferedReader b =new BufferedReader(new FileReader("I:\\Workspace\\Basic Java\\bin\\Exceptions\\List To Read.txt"));
    String s = b.readLine();
    while(s!=null){
        System.out.println(s);
        s=b.readLine();
    }
    }
    catch(RuntimeException e){
        throw e;
    }
    catch(FileNotFoundException e){
        throw e;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    }

And my main class looks like

public class TheMain {
public static void main(String args[]){
    ExceptionTest.ReadFile();
}
}

my doubt is can we throw a run time exception? Please help

Was it helpful?

Solution

RunTimeException is an unchecked exception. You can throw it, but you don't necessarily have to, unless you want to explicitly specify to the user of your API that this method can throw an unchecked exception. But even this doesn't seem to be necessary if you mention this fact (that the method can throw a RunTimeException) in the javadoc for this method.

So, in short, yes, you can throw it, but you don't have to, as it does not provide you any given advantage and costs you a few extra lines of code

OTHER TIPS

You can throw a java.lang.RuntimeException (or any derived exception), as it is a normal exception. The difference to other exceptions is that you do not need to mention it in the list of thrown but uncaught exceptions a method can throw, ie.

public void foo(int bar) throws RuntimeException {
    throw new RuntimeException("foo(bar)");
}

has the same effect as

public void foo(int bar) {
    throw new RuntimeException("foo(bar)");
}

Despite that, a java.lang.RuntimeException (or anything derived) behaves like a normal exception, ie. it terminates your program, if not caught.

throw new RuntimeException('someMessagehere')

Ideally Runtime exception should never be thrown deliberately. Java has categorised exception in Checked Exception and Unchecked i.e Runtime exception. We should always throw checked exception. The unchecked exceptions should never occur in the program as they are supposed to be handled programmatically and not by throwing them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top