1

When throwing a custom exception using throws keyword I need to handle it explicitly, i. e. I need to call the method inside the try-catch block, but while throwing an built-in exception using throws keyword if I don't handle it inside the main method using try-catch block then I don't get any compile time error it is acceptable that a runtime exception occurs. My question is when I don't handle custom exception then I get a compile time error stating: unhandled exception. While this is not the case with built-in exceptions

class B
{
   public void show() throws ArithmeticException
   {
        throw new ArithmeticException();
   }
}

public class Myclass {

     public static void main(String[] args) {
     B b = new B();
     b.show();
 }
}

when I compile the above code without handling the Arithmetic exception then I don't get any compile time error

class A extends Exception
{
    public A()
    {
       System.out.println("Exception thrown");
    }
}

class B extends A
{
    public void show() throws A
    {
        throw new A();
    }
}

public class Myclass {

   public static void main(String[] args) {
        B b = new B();
        b.show();
    }
}

but when I compile the above code it gives me an compile time error saying that I have not handled exception of type A. So, my question is why it is allowable not to handle built-in exception while it is compulsory to handle custom exceptions.

Dimitar
  • 4,402
  • 4
  • 31
  • 47
Dev Joshi
  • 73
  • 1
  • 1
  • 8

1 Answers1

1

So my question is why it is allowable not to handle built-in exception, while it is compulsory to handle custom exceptions?

It is not. It really depends on your "custom exception". If this is unchecked, there is no way to check it at compile-time - e.g. ArithmeticException. Why? Because, it has to actually perform the operation to find out, if the division is by zero and throw the exception, and this happens only at runtime. Therefore an unchecked exception always extends RuntimeException.

So a checked exception is one that could be checked at compile time. Therefore it is (explicitly) handled too, at compile-time.

Dimitar
  • 4,402
  • 4
  • 31
  • 47