Errors typically occur when something goes wrong in your program, and could range from syntax errors, logical errors or runtime errors. A syntax error occurs when the compiler does not understand your code because you violated the grammar rules of the programming language. Logical errors occur when your program does not do what you intended because of a mistake in the program's logic. Runtime errors are those that occur during runtime, caused by doing something like dividing by zero, or dealing with null data.
Exceptions on the other hand, are types of runtime errors. The difference is that exceptions can be caught and handled within the code, giving the programmer the opportunity to control the system's reaction to the error. This makes the system robust and resilient. The above code demonstrates an example of an exception. Here, we are trying to divide a number by zero, which is not permitted, and the program will throw an exception. This exception is caught and handled by providing an error message to the end user. The 'throw' statement allows you to create your own exceptions. We 'throw' an exception when a problem is detected which we cannot handle.
xxxxxxxxxx
using namespace std;
int main() {
int num1 = 5;
int num2 = 0;
int result;
try {
if (num2 == 0)
throw 0;
result = num1 / num2;
cout << result;
}
catch (int e) {
cout << "Error: Division by zero is not allowed.";
}
return 0;
}