Exception Handling in C++ and Java
Exception handling is a mechanism to handle runtime errors and unexpected situations that may occur in a program. It allows the program to gracefully handle these errors and continue execution instead of crashing.
Syntax
C++
try {
// code that might throw an exception
}
catch (exception_type e) {
// code to handle the exception
}
catch (...) {
// default catch block to handle any other exceptions
}
Java
try {
// code that might throw an exception
}
catch (ExceptionType e) {
// code to handle the exception
}
catch (Exception e) {
// default catch block to handle any other exceptions
}
finally {
// code that is executed whether or not an exception is thrown
}
Example
C++
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
try {
if (b == 0) {
throw "Division by zero";
}
cout << "Result: " << a/b << endl;
}
catch (const char* msg) {
cout << "Error: " << msg << endl;
}
return 0;
}
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int a, b;
try {
System.out.print("Enter two numbers: ");
a = input.nextInt();
b = input.nextInt();
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
System.out.println("Result: " + a/b);
}
catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
input.close();
}
}
}
Output
C++
Enter two numbers: 10 0
Error: Division by zero
Java
Enter two numbers: 10 0
Error: Division by zero
Explanation
In the above examples, we have used the try-catch block to handle a possible division by zero error. If the exception is caught, the program prints an error message instead of crashing.
In the C++ example, we have thrown a character array as an exception message. In the Java example, we have thrown an ArithmeticException object with a custom message.
Use
Exception handling is used to deal with unexpected situations that may occur during program execution. It is especially useful in situations where user input or external data is involved.
Important Points
- Exception handling is a mechanism to gracefully handle runtime errors and unexpected situations in a program.
- Exceptions can be caught and handled using the try-catch block.
- In C++, exceptions are thrown using the "throw" keyword followed by an exception message.
- In Java, exceptions are thrown using an Exception object.
- The "finally" block in Java is used to execute code that is always executed, whether or not an exception is thrown.
Summary
In summary, exception handling is an important mechanism to handle runtime errors and unexpected situations in a program. It allows the program to gracefully handle errors and continue execution instead of crashing. The try-catch block is used to catch and handle exceptions, and the "throw" keyword or an Exception object is used to throw exceptions.