top of page
Writer's pictureriyaarvadia178

Exception in Inheritance

Case 1 : Parent class throwing any exception(checked/unchecked)

If exception(checked/unchecked) is thrown in the parent class’s method then child class’s overridden method is not forced to through an exception. However it can through the exception if it wants(rules will apply).

a) Exception thrown in the parent class’s method is checked type. If the exception is thrown by the parent’s class method then child class’s overridden method may not be required to throw the exception (not mandatory but it can throw) Here, you can check the example.


class Parent{
	
	void method1()  throws SQLException {
		
	}
}

class Child extends Parent{
	
	void method1()  {
		
	}
}

b) Exception thrown in the parent class’s method is unchecked type.


If the exception is thrown by the parent’s class method then child class’s overridden method may not be required to throw the exception(not mandatory but it can throw)

class Parent{
	
	void method1()  throws RuntimeException {
		
	}
}

class Child extends Parent{
	
	void method1()  {
		
	}
}
Case 2 : Child class throwing checked exception

If the child class is throwing any checked exception then parent must also through same exception (OR) any of its parent exception otherwise compilation fails.


class Parent{
	
	void method1() throws SQLException {
		
	}
}

class Child extends Parent{
	
	void method1() throws SQLException {
		
	}

Case 3 : Child class throwing unchecked exception

If the child is throwing any unchecked exception then parent need not to throw exception.

class Parent{
	
	void method1()   {
		
	}
}

class Child extends Parent{
	
	void method1() throws RuntimeException {
		
	}
}

Here is the main rules of Exception Handling with Method OverLoading.



Parent Method

Child Method

Blank

No Exception, Any checked Exception, No Checked Exception.

RunTime Exception (UnChecked Exception)

No Exception, Any unchecked, No Checked Exception

CompileTime Exception (Checked Exception)

No Exception, Any unchecked, same checked exception or sub-type of checked exception.



0 views0 comments

Recent Posts

See All

Battle of the Backends: Java vs Node.js

Comparing Java and Node.js involves contrasting two distinct platforms commonly used in backend development. Here’s a breakdown of their...

Comments


bottom of page