Exceptions in Constructors

Medium Exception Handling in OOP
Solve in Playground →

Problem Statement

Create a `Database` class. In its constructor, if the provided integer `id` is negative, throw `std::invalid_argument(“Invalid ID”)`. Otherwise, print ‘Connected’. In `main()`, wrap the object instantiation in a try-catch block and print the error using `e.what()`.

Input Format

A single integer.

Output Format

Print 'Connected' or the exception message.

Constraints

None

Sample Input

-5

Sample Output

Invalid ID

Explanation

If a constructor cannot safely initialize an object, throwing an exception halts the creation instantly, preventing a broken object from existing in memory.

Starter Code

#include <iostream>
#include <stdexcept>

class Database {
public:
    Database(int id) {
        // Validate and throw if necessary
    }
};

int main() {
    // Read input, wrap instantiation in try-catch
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used