Intermediate C++ Game Programming Tutorial 22
From Chilipedia
In this video we learn how to use C++ exceptions to take our error handling to the next level. There is a lot of fear and ignorance surrounding exceptions among "C++ Programmers", and Chili's goal here is to elevate you guys above the shit-tier level to coders who can actually use this feature to its full extent. The second part of this tutorial will give concrete, practical examples of using exceptions in an actual game scenario.
Contents
[hide]Topics Covered
- Basic exception
try
ingthrow
ing andcatch
ing - Exceptions 'bubbling up'
- Rethrowing with
throw
-
catch(...)
-
std::exception
and its derivatives - Polymorphism in exception handling
- Exceptions and destructors
-
noexcept
and move constuctors vs. standard containers - Throw by value, catch by
const
reference
Video Timestamp Index
[Expand]
- Intro: exceptions are the main way of handling errors in C++ 0:10
- Comparing error handling with and without exceptions 1:40
- Example code to demonstrate
try
,throw
,catch
of astd::runtime_error("...")
3:53
- Use
catch(...)
to catch any uncaught excepions 8:55
- Good practice: only throw exception objects that inherit from the
std::exception
class 9:51
-
std::exception
and its derivatives 10:49
- Unwinding the stack: what happens to objects when throwing out of scope 13:39
- Exceptions and destructors 17:17
- Move semantics and containers 18:34
- Best practices 21:56
- Exceptions, applied in practice RPG Project Twin in the Chili Framework 0:10
- A custom class
ChiliException
was defined (not recommended) that holds message, filename and line number information and virtual functions for information getters defined in derived classes - An inner class
Graphics::Exception
was defined that inherits fromChiliException
and adds a data member of typeHRESULT>
(used in DirectX) - The Windows API doesn't use exceptions, so individual tests for every function using
FAILED
calls are used to throw exceptions. Macros such asCHILI_GFX_EXCEPTION()
are used to generate the exceptions - In
Main.cpp
, Chili uses a try{} inside another try{}. The first is used to test if the creation of aMainWindow
object succeeds, the second to throw exceptions usingwnd.ShowMessageBox()
of thatMainWindow
class
- A custom class
- The use of macros to generate exceptions
- A macro
CHILI_GFX_EXCEPTION()
is implemented that expands to a constructor forGraphics::Exception()
, that also takes two pre-processor defined macros (defined by the compiler):
- -
_CRT_WIDE(__FILE__)
, for the filename - -
__LINE__
, for the line number in the code
- Yu need to use a macro for this to get the line number of each function call at the different throw points (instead of the line number of the function definition)
- A macro
Extra Discussion
I had an interesting exchange with a viewer, and made a bit of a writeup here: essay time.