Home

CatchBlock

CatchBlock is a construct used in exception handling to define code that should run when an exception is thrown from a protected region, typically a try block. A catch block specifies the type of exception it can handle and contains statements to respond to the error, which may include logging, cleanup, user messages, or recovery.

When an exception is thrown, control transfers to the first catch block whose type matches the exception.

Across languages the exact syntax differs. In Java: try { ... } catch (IOException ex) { ... }. In C#: try { ... }

Common considerations include ordering catch blocks from most specific to most general, avoiding catching generic exceptions

See also: exception handling, try block, finally block.

If
a
matching
catch
block
is
found,
normal
execution
resumes
inside
that
block.
If
no
match
is
found,
the
exception
propagates
up
the
call
stack
until
it
is
caught
or
the
program
terminates.
Some
languages
also
provide
a
finally
block,
which
executes
after
catch
processing
whether
or
not
an
exception
occurred,
often
used
for
resource
cleanup.
catch
(FileNotFoundException
ex)
{
...
}.
In
JavaScript:
try
{
...
}
catch
(err)
{
...
}.
In
C++:
try
{
...
}
catch
(const
std::exception&
e)
{
...
}.
Some
languages
support
multi-catch,
allowing
a
single
block
to
handle
multiple
exception
types,
while
others
require
separate
catch
clauses
for
each
type.
unless
necessary,
and
rethrowing
or
wrapping
exceptions
when
appropriate
to
preserve
context.
Catch
blocks
should
perform
minimal
work
and
delegate
complex
recovery
to
higher
levels
when
possible.