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
3 answers

Why would an exception cause resource leaks in Node.js?

If you look at the beginning of the Node.js documentation for domains it states: By the very nature of how throw works in JavaScript, there is almost never any way to safely "pick up where you left off", without leaking references, or creating some…
26
votes
5 answers

Python thread pool that handles exceptions

I've been looking around a good implementation of a simple python thread pool pattern and really can't find anything that suits my needs. I'm using python 2.7 and all the modules I have found either don't work, or don't handle exceptions in the…
xApple
  • 6,150
  • 9
  • 48
  • 49
26
votes
7 answers

Understanding the Java stack

There is this code: public class Main { public static void main(final String[] args) throws Exception { System.out.print("1"); doAnything(); System.out.println("2"); } private static void doAnything() { …
sarkiroka
  • 1,485
  • 20
  • 28
26
votes
14 answers

Entity Framework Code First Migration Error

I'm new to MVC 4 and entity framework and when I run this command from the package manager console: Enable-Migrations -ContextTypeName MyFirstMvcApp.Models.InventoryDbContext Join-Path : Cannot bind argument to parameter 'Path' because it is…
Rafferty
  • 937
  • 1
  • 9
  • 16
26
votes
3 answers

Use single Elmah.axd for multiple applications with single DB log

We have a single SQL Log for storing errors from multiple applications. We have disabled the elmah.axd page for each one of our applications and would like to have a new application that specifically displays errors from all of the apps that report…
RSolberg
  • 26,821
  • 23
  • 116
  • 160
26
votes
6 answers

UnauthorizedAccessException cannot resolve Directory.GetFiles failure

Directory.GetFiles method fails on the first encounter with a folder it has no access rights to. The method throws an UnauthorizedAccessException (which can be caught) but by the time this is done, the method has already failed/terminated. The code…
Ric
  • 683
  • 2
  • 11
  • 19
26
votes
8 answers

Error Handling without Exceptions

While searching SO for approaches to error handling related to business rule validation, all I encounter are examples of structured exception handling. MSDN and many other reputable development resources are very clear that exceptions are not to be…
James
  • 1,788
  • 4
  • 22
  • 28
26
votes
2 answers

Capybara: exception trace in log

While running integration tests in capybara, having app raise an exception (500 error; is rendered in browser) there's no stack trace in test.log file. Here's the only line I see there: Completed 500 Internal Server Error in 25ms Am I missing…
ulmen
  • 322
  • 3
  • 8
25
votes
2 answers

Suppress first chance exceptions

Is it possible to suppress first chance supressions in Visual Studio (C# debugger) for specific lines of code? I want to use first chance exceptions in the debugger, but there are about 50 first chance exceptions I need to go through every debug…
25
votes
5 answers

What to throw when throwing C++ exceptions?

This might be kind of a silly question, but in C++, when I want to throw an exception.. what do I throw? Am I supposed to throw std::exception, or is that reserved by the standard library? Or should I throw a string or int? Or should I just throw…
user2058002
25
votes
2 answers

What exception class to use for file parsing error?

I'm writing a parser for a certain file format. If a file is not correctly formatted (and can not be parsed) then the parser throws an exception. What exception class, in the Python 2 exception hierarchy, should I use?
Johan Råde
  • 20,480
  • 21
  • 73
  • 110
25
votes
9 answers

Is it possible to execute the code in the try block again after an exception in caught in catch block?

I want to execute the code in the try block again after an exception is caught. Is that possible somehow? For Eg: try { //execute some code } catch(Exception e) { } If the exception is caught I want to go in the try block again to "execute some…
Infant Dev
  • 1,659
  • 8
  • 24
  • 48
25
votes
2 answers

Exception shows developer's path instead of servers

When an exception occurs with any ASP.NET project (possibly any .net app) the stack trace will show the path on the developer's machine, even when in production. How to change it? What's going on under the hood?
user1231231412
  • 1,659
  • 2
  • 26
  • 42
25
votes
4 answers

Wrapping calls to method on a class with a standard try/catch

I have a class that has about 200+ methods, each of these methods makes a call into the database, or a network resource. Ideally, I would like to wrap each call in a try/catch, to catch any of the common network or SQL exceptions, and give the user…
Rich S
  • 3,248
  • 3
  • 28
  • 49
25
votes
5 answers

python, __slots__, and "attribute is read-only"

I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows: class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) #…
grigoryvp
  • 40,413
  • 64
  • 174
  • 277