How to throw an exception in Java, tried code below but it raised a compilation error
class Demo{
public static void main(String args[]) {
throw new Exception("This is not allowed");
}
}
Answer
Exception and its subclasses (besides RuntimeException and its subclasses) cannot be thrown without a try-catch clause, or a throws Exception in the method declaration.
You'll need to declare your main as
public static void main(String[] args) throws Exception {
or instead of an Exception, throw a RuntimeException (or its subclass).
No comments:
Post a Comment