Difference between exception handling in C++ and Java?

前端 未结 5 1800
孤城傲影
孤城傲影 2021-02-04 00:45

In Java, if a specific line of code causes the program to crash, then the exception is caught and the program continues to execute.

However, in C++, if I have a piece of

5条回答
  •  醉话见心
    2021-02-04 01:21

    Actually, you CAN catch system exceptions in C++. There is a compiler option (at least in Visual Studio) that lets you catch access violation exceptions (which is why your program crashes).

    Java is more guarded, therefor the illusion of complexity.

    Think of the following:

    In Java:

    int x[10];
    int i = 20;
    try
    {
        int k = x[i];
    }
    catch (ArrayIndexOutOfBoundsException ex)
    {
         //will enter here
    }
    

    Int C++:

    int x[10];
    int i = 20;
    try
    {
        if ( i >= 10 )
            throw new "Index out of bounds";
        int k = x[i];
    }
    catch (...)
    {
        //now it will enter here
    }
    

    It all has to do with whether you want to leave more up to the runtime environment (like in Java's case) or you yourself want to handle things. C++ gives you more control, but you have to pay more attention.

    Your Java program would also crash if exceptions wouldn't be handled - think about it, if a method throws an exception explicitly, you can't not handle it, because the compiler doesn't let you. If not explicitly, your program will still crash unless surrounded by try/catch.

    If what you're asking why system exceptions can't be handled in C++, I already answered: they can, it's just that, by default, this is turned off.

提交回复
热议问题