Questions tagged [exception]

An exception is an unusual condition that requires deviation from the program's normal flow. Normally, an exception should not result in total failure, but instead be attended by an exception handler. Exception handling is a built-in construct in many programming languages. Usually, exceptions are handled by unwinding the stack, thus rolling back to a defined state outside the exception's scope, and then invoking a handler block or routine.

General

Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions, special conditions that change the normal flow of program execution. When such conditions occur the programmer can decide to "throw" or "raise" an exception. The thrown exception will propagate up the stack until "caught" by an appropriate language construct, which usually contains code that deals with the situation. Unhandled exceptions usually lead to abnormal termination.

Programming languages differ considerably in their support for exception handling (as distinct from error checking, which is normal program flow that checks for contingencies such as unsuccessful termination of invoked operations). In some programming languages, there are functions that cannot be safely called on invalid input data, or functions that return values which cannot be distinguished from exceptions. For example, in the atoi (ASCII to integer conversion) function may return 0 (zero) for any input that cannot be parsed into a valid value. In such languages, the programmer must either perform error checking (possibly through some auxiliary global variable such as C's errno) or input validation (perhaps using regular expressions) or both.

Exception handling is built upon three keywords: try, catch, and throw.

  • try: A try block identifies a block of code for which particular exceptions will be activated. It is followed by one or more catch blocks.
  • throw: A program throws an exception when a problem shows up. This is done using the throw keyword.
  • catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.

A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following:

try
{
   // protected code
}
catch( ExceptionName e1 )
{
   // catch block
}
catch( ExceptionName e2 )
{
   // catch block
}
catch( ExceptionName eN )
{
   // catch block
}

You can provide multiple catch statements to catch different types of exceptions in case your try block raises more than one type of exception.

Exception safety

Exception safety, as formalised by David Abrahams, guarantees a set of contract guidelines that an interface (or operation) offers w.r.t. the state of the program if an exception occurs.

  1. No-throw guarantee: the operation is guaranteed not to fail
  2. Strong exception safety: if the operation fails, the state will be as it was prior to the failure (rollback semantics)
  3. Basic exception safety: no leaks will occur, and data is left in a valid state (but possibly changed)
  4. No exception safety: no guarantees are made.

Automated exception handling

Automated exception handling is a computing term referring to the computerized handling of errors. Runtime engines such as those for the Java language or Microsoft .NET lend themselves to an automated mode of exception or error handling. In these environments, software errors do not "crash" the program or operating system but rather generate exceptions. Recent advances in these runtime engines enable specialized runtime-engine add-on products to provide automated exception handling that is independent of the source code and provides root-cause information for every exception of interest.

Tag Usage

Use this tag for

  • Questions about the technical process of how various languages, runtimes, or platforms handle (or do not handle) specific exceptions.
  • Questions about implementing custom automated exception handling capabilities.

Do not use this tag for

  • Debugging requests containing an exception as part of an MCVE, but are not otherwise about exceptions. These are questions that contain exceptions, but are not about them. One of our suggested edit rejections contains the text "Tags should help to describe what the question is about, not just what it contains."

References

Exception handling syntax

Further reading

Vexing exceptions blog post on MSDN by Eric Lippert, 2008
Cleaner, more elegant, and harder to recognize blog post on MSDN by Raymond Chen, 2005
Exception-Safe Coding in C++ web page by Jon Kalb

53429 questions
5551
votes
27 answers

How do I create a directory, and any missing parent directories?

How do I create a directory at a given path, and also create any missing parent directories along that path? For example, the Bash command mkdir -p /path/to/nested/directory does this.
Parand
  • 102,950
  • 48
  • 151
  • 186
3760
votes
6 answers

Catch multiple exceptions in one line (except block)

I know that I can do: try: # do something that may fail except: # do this if ANYTHING goes wrong I can also do this: try: # do something that may fail except IDontLikeYouException: # say please except YouAreTooShortException: #…
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
3156
votes
11 answers

Manually raising (throwing) an exception in Python

How do I raise an exception in Python so that it can later be caught via an except block?
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
2540
votes
29 answers

Catch multiple exceptions at once?

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught. Now, this sometimes leads to unnecessary repetitive code, for example: try { WebId = new Guid(queryString["web"]); } catch…
Michael Stum
  • 177,530
  • 117
  • 400
  • 535
2271
votes
35 answers

How do you assert that a certain exception is thrown in JUnit tests?

How can I use JUnit idiomatically to test that some code throws an exception? While I can certainly do something like this: @Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); …
SCdF
  • 57,260
  • 24
  • 77
  • 113
1796
votes
16 answers

Proper way to declare custom exceptions in modern Python?

What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever…
Nelson
  • 27,541
  • 5
  • 35
  • 31
1430
votes
23 answers

What is the use of "assert" in Python?

What does assert mean? How is it used?
Hossein
  • 40,161
  • 57
  • 141
  • 175
1372
votes
19 answers

Catch and print full Python exception traceback without halting/exiting the program

I want to catch and log exceptions without exiting, e.g., try: do_stuff() except Exception as err: print(Exception, err) # I want to print the entire traceback here, # not just the exception name and details I want to print the…
chriscauley
  • 19,015
  • 9
  • 33
  • 33
1371
votes
11 answers

How do I print an exception in Python?

How do I print the error/exception in the except: block? try: ... except: print(exception)
TIMEX
  • 259,804
  • 351
  • 777
  • 1,080
1348
votes
15 answers

How do I check if a variable exists?

I want to check if a variable exists. Now I'm doing something like this: try: myVar except NameError: # Do something. Are there other ways without exceptions?
Max Frai
  • 61,946
  • 78
  • 197
  • 306
1242
votes
34 answers

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Recently I ran into this error in my web application: java.lang.OutOfMemoryError: PermGen space It's a typical Hibernate/JPA + IceFaces/JSF application running on Tomcat 6 and JDK 1.6. Apparently this can occur after redeploying an application a…
Chris
  • 632
  • 4
  • 11
  • 18
1190
votes
19 answers

How do you test that a Python function throws an exception?

How does one write a unit test that fails only if a function doesn't throw an expected exception?
Daryl Spitzer
  • 143,156
  • 76
  • 154
  • 173
1103
votes
10 answers

How can I write a `try`/`except` block that catches all exceptions?

How can I write a try/except block that catches all exceptions?
user469652
  • 48,855
  • 59
  • 128
  • 165
973
votes
6 answers

Why is it bad style to `rescue Exception => e` in Ruby?

Ryan Davis’s Ruby QuickRef says (without explanation): Don’t rescue Exception. EVER. or I will stab you. Why not? What’s the right thing to do?
John
  • 29,546
  • 11
  • 78
  • 79
941
votes
12 answers

How to properly ignore exceptions

When you just want to do a try-except without handling the exception, how do you do it in Python? Is the following the right way to do it? try: shutil.rmtree(path) except: pass
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
1
2 3
99 100