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");
}
}
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");
}
}
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).
The Exception
represents exceptional event or situation which demands altered program flow.
The keywords try
, catch
, throw
, throws
, finally
facilitate the modification of program flow.
The simple idea is that Exception
s are thrown from where they occur or are found, and caught where they are intended to be handled. This allows a sudden jump in the program execution, thus achieving modified program flow.
There has to be someone who can catch it, otherwise it wouldn't be right to throw it. This is the cause of your error. You did not specify how or where would the exception be handled, and threw it in the air.
Handle it right there
class Demo{
public static void main(String args[]) {
try { // Signifies possibility of exceptional situation
throw new Exception("This is not allowed"); // Exception is created
// and thrown
} catch (Exception ex) { // Here is how it can be handled
// Do operations on ex (treated as method argument or local variable)
}
}
}
Force someone else to handle it
class Demo{
public static void main(String args[]) throws Exception { // Anyone who calls main
// will be forced to do
// it in a try-catch
// clause or be inside
// a method which itself
// throws Exception
throw new Exception("This is not allowed");
}
}
Hope this helps