Javatpoint Logo
Javatpoint Logo

Catching Base and Derived Classes as Exceptions in C++ and Java

Before diving straight into our topic, Catching Base and Derived Classes as Exceptions in C++ and Java, let us understand what exceptions and exception handling are. Exceptions are the errors which occur while we are programming and are generally treated as unwanted errors or to understand better. They are like the hurdles caused while programming, and exception handling is the error handling mechanism to treat the exceptions or the limitations that occur.

Various methods to handle exception handling and base and derived class catch as part of exception in both C++ and Java programming languages.

  • In a scenario where the base and the derived classes we have declared are caught in the mechanism as exceptions, then we must see at the display output terminal that the catch block of the said derived class appears before the type of base we declared.
  • The above statement is valid, and we can even recheck if we put our base class before the derived class, then the derived class which we have declared will never be reached.

Algorithm (Catching Base and Derived Classes as Exceptions in C++ and Java)

Example:

C++ Code

Output:

prog.cpp: In function 'int main()':
prog.cpp:20:5: warning: exception of type 'derived_' will be caught
    catch (derived_ d) {
    ^
prog.cpp:17:5: warning:    by the earlier handler for 'base_.'
    catch (base_ b) {
/ tm  p /vLt kM  pH G zo.o
OH! Caught Based Exception occurred

C++ code

Output:

/tmp /vL tk MpH  Gzo.o
the code has been caught in the derived exception

Java Code

Output:

/tmp /vL tk MpH  Gzo.o
./Main.java:13: error: exception Derived has already been caught
		catch (Derived d) {
		^
1 error

Java Code

Output:

Main.java:12: error: exception Derived has already been caught
    catch(derived_d)  { System.out.println("the code has been caught in the derived exception");}






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA