Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Comparison of Exception Handling in C++ and Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 421
    Comment on it

    Comparison of Exception Handling in C++ and Java

    In C++ and Java, keywords like try,catch and throw for exception handling are same,their meaning is also same but exception handling in C++ and Java differ in many ways.

    1)In Java only instances of subclasses of Throwable class i.e only throwable objects can be thrown as exception but in C++ any types like primitives,pointers etc can be thrown as exception.

    Program that will work in C++ but not in Java.

    #include <iostream>
    using namespace std;
    int main() 
    {
       int a = -1;    
       try 
       {
    
          if( a < 0 )
          {
             throw x;
          }   
       }
       catch (int x ) 
       {
    
          cout << "Exception occurred:value thrown is " << x << endl;
       }
       getchar();
       return 0;
    }
    

    Output:

    Exception occurred: value thrown is -1

    2)In Java to catch all kind of Exception we catch Exception object e.g catch(Exception e) but in C++ a catch all is used to catch any kind of exception.

    3)In Java there are two kinds of exceptions checked and unchecked but in C++ all exceptions are unchecked.

    4)A block called finally is executed after try catch block is executed mostly to do cleanup work.In C++ there is no such block.

    Example to demonstrate finally block in Java.

    class Demo extends Exception 
    { 
    }
    
    class Main {
    
    
     public static void main(String args[]) {
    
          try 
          {
             throw new Demo();
          }
          catch(Demo d) 
          {
             System.out.println("Got the Demo Exception");
          }
          finally 
          {
             System.out.println("Inside finally block ");
          }
      }
    }
    

    Output

    Got the Demo Exception
    Inside finally block

    5)In Java,throws keyword is used to list expected exceptions that a function can throw. In C++, there is no throws keyword, throw keyword is used instead to list expected keyword to be thrown.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: