Saturday 18 May 2019

Java exception throw




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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...