Anshul Gupta
Anshul Gupta

Reputation: 277

Unable to subclass Runtime Exception

I want to "get around" the strict restrictions placed on methods by the throws clause. So I decided to subclass RuntimeException to make up a new, exempt exception of my own. Now I can throw it to my heart's content, because the throws clause that was annoying me does not need to include this new exception but the code is not working.

public class Cnf extends RuntimeException {
    public Cnf(){};
}
    
public class Example1 { 
    public static void main(String args[]) { 
        if(Class.forName("GeeksForGeeks")==null){
            throw new Cnf();
        else
            System.out.println("Hello");
        } 
    } 
}

Upvotes: -1

Views: 599

Answers (2)

xtratic
xtratic

Reputation: 4699

Your problem is that Class.forName is the one that's throwing the exception.

Easiest, naive, solution to "get around" an exception in this way is to catch then re-throw the exception in a RuntimeException. This is much better than catching and ignoring the exception but I don't recommend this unless you are quite sure that checked exception will/must never occur. However, I do agree this is probably an ok way to handle the checked exceptions thrown by Class.forName since you're quite sure that classname will/must exist, and if it doesn't then you'll still get a clear exception at runtime just as if you dealt with the checked exceptions.

public static void main(String args[]) {
    Class<?> klass;
    try {
        klass = Class.forName("qualified.name.of.GeeksForGeeks");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    // do something with your klass...
} 

Upvotes: 2

rzwitserloot
rzwitserloot

Reputation: 102923

Let's jump straight to the real solution to your problem:

put throws Exception on your main method. Problem solved.

Now for your new fancy runtime exception: your method must either [A] catch, or [B] put in the 'throws' clause, unless it is a runtimeexception in which case you don't need do that - for all exceptions you either explicitly throw with the throw statement, OR for any method invocations you invoke, all exceptions listed on their throws line in the method signature.

The Class.forName call lists a bunch of checked exceptions. You have to handle them. Putting that call in an if doesn't change anything about that.

Upvotes: 0

Related Questions