0
0
C++programming~20 mins

Try–catch block in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Try–catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try–catch with integer exception
What is the output of this C++ code?
C++
#include <iostream>

int main() {
    try {
        throw 5;
    } catch (int e) {
        std::cout << "Caught integer: " << e << std::endl;
    }
    return 0;
}
ACaught integer: 0
BCaught integer: 5
CNo output
DCompilation error
Attempts:
2 left
💡 Hint
The throw statement throws an integer, which is caught by the catch block.
Predict Output
intermediate
2:00remaining
Output when no exception is thrown
What will this C++ program output?
C++
#include <iostream>

int main() {
    try {
        std::cout << "Inside try block" << std::endl;
    } catch (...) {
        std::cout << "Caught exception" << std::endl;
    }
    std::cout << "After try-catch" << std::endl;
    return 0;
}
A
Inside try block
After try-catch
BCompilation error
CInside try block
D
Caught exception
After try-catch
Attempts:
2 left
💡 Hint
No exception is thrown, so catch block is skipped.
Predict Output
advanced
2:00remaining
Output with multiple catch blocks
What is the output of this C++ code?
C++
#include <iostream>

int main() {
    try {
        throw 'a';
    } catch (int e) {
        std::cout << "Caught int: " << e << std::endl;
    } catch (char e) {
        std::cout << "Caught char: " << e << std::endl;
    } catch (...) {
        std::cout << "Caught unknown exception" << std::endl;
    }
    return 0;
}
ACompilation error
BCaught int: 97
CCaught unknown exception
DCaught char: a
Attempts:
2 left
💡 Hint
The thrown type is char, so the matching catch block runs.
Predict Output
advanced
2:00remaining
Exception not caught by specific catch block
What happens when this C++ code runs?
C++
#include <iostream>

int main() {
    try {
        throw 3.14;
    } catch (int e) {
        std::cout << "Caught int: " << e << std::endl;
    }
    return 0;
}
AProgram terminates with uncaught exception
BCaught int: 3
CCaught int: 3.14
DCompilation error
Attempts:
2 left
💡 Hint
The thrown type is double but catch expects int.
🧠 Conceptual
expert
3:00remaining
Behavior of nested try–catch blocks
Consider this C++ code with nested try–catch blocks. What is the output?
C++
#include <iostream>

int main() {
    try {
        try {
            throw 10;
        } catch (double e) {
            std::cout << "Inner catch double" << std::endl;
        }
    } catch (int e) {
        std::cout << "Outer catch int: " << e << std::endl;
    }
    return 0;
}
ANo output
BInner catch double
COuter catch int: 10
DCompilation error
Attempts:
2 left
💡 Hint
The inner catch does not catch int, so exception propagates to outer catch.