0

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");
    }
}
PKuhn
  • 1,338
  • 1
  • 14
  • 30

2 Answers2

3

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).

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

Exception Handling

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 Exceptions 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.


The Balance

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.


Solution

  1. 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)
            }
        }
    }
    
  2. 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

Tanmay Patil
  • 6,882
  • 2
  • 25
  • 45