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
26
votes
5 answers

Flattening of AggregateExceptions for Processing

I'm running into a few issues where I call flatten on an AggregateException, but inside there is still ANOTHER AggregateException! This obviously means that they are being propagated up the chain and being rolled into another AggregateException. …
JNYRanger
  • 6,829
  • 12
  • 53
  • 81
26
votes
1 answer

How to reduce stack trace when throwing error (point to call site)

I have a function like this: function foo() { throw new Error('`foo` has been removed in favor of `bar`') } When someone calls foo, I want the stack trace (error output) to point at the call site of foo, not the throw line inside of foo. For…
Jo Liss
  • 30,333
  • 19
  • 121
  • 170
26
votes
7 answers

Tips to help debug "Could not load file or assembly X or one of its dependencies"

I'm looking for tips/suggestions/insights to help debug an on application load issue; Could not load file or assembly... The solution/project where I'm experiencing this issue is a conversion from a working copy in Visual Studio 2008 to the Visual…
Nick Josevski
  • 4,156
  • 3
  • 43
  • 63
26
votes
5 answers

C#: Does Visual Studio 2008 have a tool to show which Exceptions could be raised by a piece of code?

For example, if I'm opening a file, I know a FileNotFoundException might happen, or if I'm converting a String to double, a FormatException may happen. Obviously, if a method does both, both can be raised. Is there a way to quickly see all possible…
zxcvbnm
  • 1,833
  • 3
  • 27
  • 35
26
votes
3 answers

python isinstance vs hasattr vs try/except: What is better?

I am trying to figure out the tradeoffs between different approaches of determining whether or not with object obj you can perform action do_stuff(). As I understand, there are three ways of determining if this is possible: # Way 1 if…
Felix
  • 2,064
  • 3
  • 21
  • 31
26
votes
10 answers

Try..Catch blocks always expensive?

Possible Duplicate: Do try/catch blocks hurt performance when exceptions are not thrown? Hey everyone, Just a quick question about try..catch blocks. I've heard they're expensive to use and shouldn't be used as part of a program's flow.…
Skoder
  • 3,983
  • 11
  • 46
  • 73
26
votes
3 answers

How to catch an exception in python and get a reference to the exception, WITHOUT knowing the type?

I'm wondering how I can catch any raised object (i.e. a type that does not extend Exception), and still get a reference to it. I came across the desire to do this when using Jython. When calling a Java method, if that method raises an exception,…
TM.
  • 108,298
  • 33
  • 122
  • 127
26
votes
4 answers

UnexpectedRollbackException - a full scenario analysis

All I know about this exception is from Spring's documentation and some forum posts with frostrated developers pasting huge stack traces, and no replies. From Spring's documentation: Thrown when an attempt to commit a transaction resulted in an…
Eran Medan
  • 44,555
  • 61
  • 184
  • 276
26
votes
4 answers

The throws keyword for exceptions in Java

when you do this: public class Blah { public void doBlah() throws BlahException { } } What does adding the throws BlahException really do? Does it basically group any exception to that one? i.e. if there is an exception, no matter what…
mrblah
  • 99,669
  • 140
  • 310
  • 420
26
votes
18 answers

Avoiding null reference exceptions

Apparently the vast majority of errors in code are null reference exceptions. Are there any general techniques to avoid encountering null reference errors? Unless I am mistaken, I am aware that in languages such as F# is it not possible to have a…
Nippysaurus
  • 20,110
  • 21
  • 77
  • 129
26
votes
7 answers

Spring 3.2 @ControllerAdvice Not Working

I am having trouble getting @ControllerAdvice to work. I updated my namespace location, which were 3.1 in my xml files. I moved the class with the controller to the same package as the controller. I am using 3.2.0 release jars. If I put the…
Joe
  • 747
  • 3
  • 8
  • 21
26
votes
7 answers

Throwing an exception from within a signal handler

We have a library that deals with many aspects of error reporting. I have been tasked to port this library to Linux. When running though my little test suite, one of the tests failed. A simplified version of the test appears below. // Compiler:…
EvilTeach
  • 28,120
  • 21
  • 85
  • 141
26
votes
2 answers

First chance exception - long at memory location?

What is this and how can I handle/fix it? First-chance exception at 0x756fb727 in Program.exe: Microsoft C++ exception: long at memory location 0x0018f7a4. I am getting about a thousand of these each time I run my application. How can I track this…
Chris
  • 21,549
  • 25
  • 71
  • 99
26
votes
6 answers

Is there an equivalent in T-SQL to C#'s "throw;" to re-throw exceptions?

The title really is the question for this one: Is there an equivalent in T-SQL to C#'s "throw;" to re-throw exceptions? In C# one can do this: try { DoSomethingThatMightThrowAnException(); } catch (Exception ex) { // Do something with the…
Neil Barnwell
  • 41,080
  • 29
  • 148
  • 220
26
votes
3 answers

'sys.excepthook' and threading

I am using Python 2.5 and trying to use a self-defined excepthook in my program. In the main thread it works perfectly fine. But in a thread started with the threading module the usual excepthook is called. Here is an example showing the problem.…
Sebastian
  • 261
  • 1
  • 3
  • 3