So far we have created programs in which we assumed that user would never input wrong data, code would never have bugs and programs always work properly without any error.
- [#1] – Introduction to C++ – Questions
- [#2] – Preparing and Running C++ Program – Questions
- [#3] – C++ Fundamentals – Questions
- [#4] – Data Input and Output – Questions
- [#5] – Control Structures – Questions
- [#6] – Functions – Questions
- [#7] – Arrays and Strings – Questions
- [#8] – Structures and Unions – Questions
- [#9] – Pointers – Questions
- [#10] – Object and Classes – Questions
- [#11] – Constructors and Destructors – Questions
- [#12] – Operator Overloading and Type Conversion – Questions
- [#13] – Inheritance – Questions
- [#14] – Virtual Functions – Questions
- [#15] – C++ Streams and Files – Questions
- [#16] – Templates – Questions
- [#17] – Exception Handling – Questions
However, it is very rare to run the program successfully at very first attempt without any errors. Practically, every program may encounter various types of errors which produce an unexpected output or terminate the execution of the program abnormally or even may result in system crash.
The errors that occur at run time are known as exceptions.
Key Points To Remember –
- The errors that occur at run time are known as exceptions. The occur due to different conditions such as division by zero, accessing an element that is out of bound of an array, unable to open a file, running out of memory and many more.
- The exceptions are handled by creating a try-catch block. In the try block, we define the statement(s) that needs to be tested for exception(s) and if an exception occurs, we use the ‘throw’ statement to invoke an exception handler.
- In order to handle multiple exceptions of different types, we need to define multiple catch blocks associated with a single try block. Each of the multiple catch block defined take parameters of different data types and each must match a different type of exception.
- The catch(…) block handles an exception if it is not handled by any of the other catch block defined above.
- When a single catch block may not handle an exception completely then in such a situation, the catch block on receiving an exception must pass it to another catch block by rethrowing the exception.
- The exception specification helps you to throw a list of exceptions that a function can throw.
Similar Questions –
- What are exceptions ?
- How is an exception handled in C++ ?
- What is the need of exception handling ?
- What is the purpose of keyword try, catch and throw in exception handling.
- What should be placed inside a try block and a catch block ?
- What happens when a raised exception is not caught by any of the catch block ?
- What is the need of multiple catch blocks ? How is it defined?
- How will you handle all the exceptions with a single catch block ?
- Why do we rethrow an exception ?
- What is an exception specification ? When is it used ?