Exception Handling in Method Overriding

There are certain rules that you must learn in method overriding involving exception handling. These rules are-

1. If a base class method does not declare a checked exception, then overriding method in a derived class cannot declare a checked exception, but it can declare unchecked exception

class Parent
{
	void myMethod1(){}
	void myMethod2(){}
}
class Child extends Parent
{
	void myMethod1(){}
	void myMethod2() throws RunTimeException{}
}

2. If a base class method declares a checked exception, then it is not compulsory for an overriding method in a derived class to declare any checked exception

class Parent
{
	void myMethod() throws IOException{}
}
class Child extends Parent
{
	void myMethod(){}
}

3. If a base class method declares a checked exception, then overriding method in a derived class cannot declare exception which is superclass of the exception declared by its base class

class Parent
{
	void myMethod() throws IOException{}
}
class Child extends Parent
{
	void myMethod() throws Exception{}
}
Compile Time Error

4. If a base class method declares a checked exception, then overriding method in a derived class can declare the same exception

class Parent
{
	void myMethod() throws IOException{}
}
class Child extends Parent
{
	void myMethod() throws IOException{}
}

5. If a base class method declares a checked exception, then overriding method in a derived class can declare exception which is subclass of the exception declared by its base class

class Parent
{
	void myMethod() throws IOException{}
}
class Child extends Parent
{
	void myMethod() throws FileNotFoundException{}
}

The above code is valid because FileNotFoundException is a subclass of IOException