Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Runtime Exception can be thrown?

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

like image 929
Bhargav Avatar asked Mar 09 '26 21:03

Bhargav


2 Answers

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

like image 171
Srikanth Reddy Lingala Avatar answered Mar 11 '26 09:03

Srikanth Reddy Lingala


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.

like image 43
Abrixas2 Avatar answered Mar 11 '26 09:03

Abrixas2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!