Exceptions and Errors
Exceptions and Errors
Explanation:
- Exceptions are conditions that can be handled in the program using constructs like try, catch, and
throw.
- Errors are severe conditions often caused by hardware or memory issues and cannot be handled
programmatically.
Example Code:
#include <iostream>
void exceptionExample() {
try {
int a = 10, b = 0;
if (b == 0) {
void errorExample() {
int main() {
exceptionExample();
errorExample();
return 0;
Explanation:
Code Comparison:
Using if-else:
#include <iostream>
if (b == 0) {
} else {
int main() {
divide(10, 0);
return 0;
Using try-catch:
#include <iostream>
try {
if (b == 0) {
int main() {
divide(10, 0);
return 0;
}
3. Can throw Be Used in Constructors? If Yes, How Would You Handle It?
Explanation:
- Handle such exceptions using a try-catch block where the object is created.
Example Code:
#include <iostream>
#include <string>
class MyClass {
public:
MyClass(string name) {
if (name.empty()) {
cout << "Object created with name: " << name << endl;
};
int main() {
try {
return 0;
Visit Website