codebase - github.com/SC-Academy/CPPExceptionHandling.git
In this example, we have a function divide that performs integer division between two numbers. The function checks if the divisor (b) is zero and throws an exception with an error message if it is. The main function demonstrates the usage of exception handling:
We prompt the user to enter two numbers and store them in num1 and num2.
Inside the try block, we call the divide function with num1 and num2 as arguments. If the divisor is zero, the function throws an exception using the throw keyword.
The catch block catches the exception and handles it. In this example, we catch an exception of type const char* (a C-style string) and print the error message to the console.
If no exception is thrown, the program continues execution after the catch block.
Example scenarios:
If the user enters 10 and 5, the program calculates the result of the division (10 / 5 = 2) and prints it to the console.
Output:
Enter two numbers: 10 5
Result of division: 2
If the user enters 15 and 0, the program detects the division by zero and throws an exception. The catch block catches the exception and prints the error message.
Output:
Enter two numbers: 15 0
Exception occurred: Division by zero is not allowed.
#CPlusPlusTutorial, #ExceptionHandling, #CplusplusExceptionHandling, #BeginnersGuide, #CPlusPlusProgramming, #ErrorHandling, #ProgrammingTutorial, #Coding, #CPlusPlus
コメント