Basic try-catch in C++

Basic try-catch Block in C++.

BeginnerException Handling ProgramsExample 1 of 5
basic-try-catch.cpp
1#include <iostream>
2using namespace std;
3
4int divide(int a, int b) {
5 if (b == 0) {
6 throw "Division by zero error!";
7 }
8 return a / b;
9}
10
11int main() {
12 int num1, num2;
13
14 cout << "Enter two numbers: ";
15 cin >> num1 >> num2;
16
17 try {
18 int result = divide(num1, num2);
19 cout << "Result: " << result << endl;
20 } catch (const char* error) {
21 cout << "Error caught: " << error << endl;
22 }
23
24 cout << "Program continues after exception handling." << endl;
25
26 return 0;
27}

Output

Enter two numbers: 10 0
Error caught: Division by zero error!
Program continues after exception handling.

What's going on

The program demonstrates basic exception handling:

Throwing exceptions using throw statement
Catching exceptions using try-catch blocks
Handling division by zero error
Continuing program execution after exception

Exception handling prevents crashes and enables graceful error management.

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.

Understanding Exception Handling

Exception Concept

:

Errors or unexpected situations
Thrown when problem occurs
Caught and handled gracefully
Prevents program crashes

Key Components

:

try: code that might throw
throw: raises exception
catch: handles exception
Program continues after catch

Throwing Exceptions

Using throw

:

if (b == 0) {

throw "Division by zero error!";

}

How it works

:

throw statement raises exception
Can throw any type (string, int, object)
Control immediately jumps to catch
Code after throw not executed

Try Block

Wrapping Code

:

try {

int result = divide(num1, num2);

}

1cout << "Result: " << result << endl;

How it works

:

Code that might throw goes in try
If exception thrown, jumps to catch
If no exception, continues normally
Can have multiple statements

Catch Block

Handling Exception

:

catch (const char* error) {

}

1cout << "Error caught: " << error << endl;

How it works

:

Catches specific exception type
Executes when exception thrown
Receives exception value
Program continues after catch

When to Use Exception Handling

Best For

:

Error conditions
Invalid input
Resource failures
Unexpected situations
Robust error handling

Example Scenarios

:

Division by zero
File not found
Invalid user input
Network errors
Memory allocation failures

Important Considerations

Exception Types

:

Can throw any type
Strings, integers, objects
Standard exception classes
Custom exception classes

Program Flow

:

Exception jumps to catch
Code after throw not executed
Program continues after catch
Prevents crashes

Error Messages

:

Provide clear error messages
Help with debugging
Inform users of problems
Guide error resolution

return 0;

This ends the program successfully.