Try, Catch, and Throw inside Methods

Easy Exception Handling in OOP
Solve in Playground →

Problem Statement

Create a `Calculator` class with a method `int divide(int a, int b)`. Inside `divide`, if `b` is 0, throw a `const char*` exception with the message “Divide by zero”. Otherwise, return `a / b`. In `main()`, read two integers, call the method inside a `try` block, and `catch (const char* msg)` to print the error. If successful, print ‘Result: [val]’.

Input Format

Two space-separated integers.

Output Format

Print the result or the error message.

Constraints

None

Sample Input

10 0

Sample Output

Divide by zero

Explanation

The `throw` keyword instantly stops method execution and passes the error to the nearest `catch` block in the call stack.

Starter Code

#include <iostream>

class Calculator {
public:
    int divide(int a, int b) {
        // Write your throw logic here
        return 0;
    }
};

int main() {
    // Implement try-catch block here
    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