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

Throw Exception inside a Task - "await" vs Wait()

static async void Main(string[] args) { Task t = new Task(() => { throw new Exception(); }); try { t.Start(); t.Wait(); } catch (AggregateException e) { // When waiting…
Yaron Levi
  • 12,535
  • 16
  • 69
  • 118
25
votes
1 answer

Getting Security exception while trying to fetch networkcapabilities on android 11

I am getting SecurityException followed by RemoteException while trying to access below code. API val networkCapabilities = connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork) Exception getting Fatal Exception:…
25
votes
3 answers

Programmatically determine whether exceptions are enabled

Most C++ compilers allow for exceptions to be disabled. Is there a way to determine it from the code without using compiler-specific preprocessor macros, such as _CPPUNWIND for MSVC? Ideally at compile time.
Nemanja Trifunovic
  • 24,346
  • 3
  • 50
  • 88
25
votes
5 answers

Tool to extract java stack traces from log files

Is there any tool that can extract a list of stack traces appearing in the log file and probably count unique ones? EDIT: I would preffer something that is not GUI-based and be run on the background and give some kind of report back. I have quite…
Andrey Adamovich
  • 20,285
  • 14
  • 94
  • 132
25
votes
6 answers

What happens if a method throws an exception that was not specified in the method declaration with "throws"

I've never used the "throws" clause, and today a mate told me that I had to specify in the method declaration which exceptions the method may throw. However, I've been using exceptions without problems without doing it, so, why is it needed if, in…
bluehallu
  • 10,205
  • 9
  • 44
  • 61
25
votes
3 answers

Don't show Python raise-line in the exception stack

When I raise my owns exceptions in my Python libraries, the exception stack shows the raise-line itself as the last item of the stack. This is obviously not an error, is conceptually right, but points the focus on something that is not useful for…
Htechno
  • 5,901
  • 4
  • 27
  • 37
25
votes
6 answers

Is there any way to start task using ContinueWith task?

My code: var r = from x in new Task(() => 1) from y in new Task(() => x + 1) select y; r.ContinueWith(x => Console.WriteLine(x.Result)).Start(); or new Task(() => 1) .ContinueWith(x =>…
dotneter
  • 1,689
  • 2
  • 15
  • 24
25
votes
2 answers

Get name of specific Exception

Is this the best method for getting the name of a specific Exception in C#: ex.GetType().ToString() It is in a generic exception handler: catch (Exception ex)
Robben_Ford_Fan_boy
  • 8,494
  • 11
  • 64
  • 85
25
votes
1 answer

How do I handle JavaScript Fetch errors?

If a fetch call fails in Chrome, then the only error details that I get back is TypeError: Failed to fetch How do I display an informative error message to the end user in this case? Specifically: Is it possible to get any details about why fetch…
Josh Kelley
  • 56,064
  • 19
  • 146
  • 246
25
votes
8 answers

ANSI C equivalent of try/catch?

I have some C code I'm working with, and I'm finding errors when the code is running but have little info about how to do a proper try/catch (as in C# or C++). For instance in C++ I'd just do: try{ //some stuff } catch(...) { //handle error } but…
aiden
  • 259
  • 1
  • 3
  • 3
25
votes
5 answers

How do you document unchecked exceptions?

Joshua Bloch in his Effective Java writes : "Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration. " Well that sounds…
Xorty
  • 18,367
  • 27
  • 104
  • 155
25
votes
5 answers

Why doesn't C++ use std::nested_exception to allow throwing from destructor?

The main problem with throwing exceptions from destructor is that in the moment when destructor is called another exception may be "in flight" (std::uncaught_exception() == true) and so it is not obvious what to do in that case. "Overwriting" the…
anton_rh
  • 8,226
  • 7
  • 45
  • 73
25
votes
7 answers

System.exit(num) or throw a RuntimeException from main?

I've got a single threaded app that should set the DOS errorlevel to something non-zero if there is a problem. Is it better to throw a RuntimeException, or to use System.exit(nonzero)? I don't need the stack trace, and I don't expect this app to be…
VarV
  • 253
  • 1
  • 3
  • 5
25
votes
7 answers

The socket connection was aborted - CommunicationException

Originally: I thought this was a circular reference problem........turns out it's not. The problem arose from having not configured the service configurations at all. Since the defaults are very low, sending lots of data will make the service…
Goober
  • 13,146
  • 50
  • 126
  • 195
25
votes
3 answers

DatePicker crash in samsung with android 5.0

I am having trouble with creating a datepicker in samsung note 2 device with lollipop 5.0. The exception is: java.util.IllegalFormatConversionException: %d can not format java.lang.String arguments at…