with C++ Lecture 19
Introduction to Exceptions
1. Overview
o Exceptions are a mechanism for handling errors that disrupt
the normal flow of a program. They provide a way to separate
error-handling code from regular business logic, making
programs more readable and maintainable.
2. Logic and Runtime Errors
o Logic errors are bugs in the code, such as incorrect logic or
algorithm. Runtime errors occur during the execution of a
program, such as file not found or out-of-memory errors.
Example:
3. Exception Safety
o Exceptions add a degree of safety by allowing programs to
handle unforeseen events. They prevent the mixing of
business logic and error-handling code, which can lead to
more maintainable and robust systems.
, Exceptions in C++ vs. Java
1. C++ Exception Handling
o C++ uses exceptions primarily for error handling. It allows
throwing and catching exceptions of any data type and
includes the noexcept keyword to specify functions that do not
throw exceptions.
2. Java Exception Handling
o Java uses exceptions for various purposes, including error
handling and flow control. It has checked exceptions (which
must be caught or declared) and unchecked exceptions. Java
provides finally blocks for cleanup, which C++ achieves using
RAII (Resource Acquisition Is Initialization).
Keywords and Syntax
1. Key Keywords
o try: Defines a block of code that may throw exceptions.
o catch: Catches and handles exceptions thrown in the try
block.
o throw: Used to throw an exception.
Example:
2. Noexcept Keyword
o Indicates that a function does not throw exceptions. If a
noexcept function does throw, std::terminate is called.
Example: