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

Pass object (List) as part of Exception

I am constructing a list of strings and then want to throw an exception and let the UI handle the list and create the error message for the user. Is there a way to do that?
Pacman
  • 2,183
  • 6
  • 39
  • 70
25
votes
3 answers

Try / Catch in Constructor - Recommended Practice?

Something I've always been curious of public class FileDataValidator { private String[] lineData; public FileDataValidator(String[] lineData){ this.lineData = lineData; removeLeadingAndTrailingQuotes(); try { …
deanmau5
  • 861
  • 7
  • 17
  • 27
25
votes
2 answers

(not) using std::string in exceptions

I'm always reading that I should not to throw a std::string or some other classes allocating memory. like here or more importantly here on point 3. - Don't embed a std::string object. So now I'm trying to insert boost::exception to my project and…
user1810087
  • 5,146
  • 1
  • 41
  • 76
25
votes
3 answers

Printing Exception Message in java

Is there a way to print an exception message in Java without the exception? When I try the following piece of code: try { // statements } catch (javax.script.ScriptException ex) { System.out.println(ex.getMessage()); } The output…
sony
  • 1,557
  • 10
  • 36
  • 50
25
votes
1 answer

Quick way to toggle 'break on all exceptions' in VS2012?

I regularly find it very useful when debugging to switch on the Common Language Runtime Exceptions: Thrown option in Visual Studio's Debug > Exceptions screen. I'd like a quick way of doing this, since it's always the same checkbox I'm toggling and…
25
votes
4 answers

A method was called at an unexpected time

I'm trying to iterate all files in a directory using GetFilesAsync, but every time I call the GetResults method, it throws an exception that says System.InvalidOperationException: A method was called at an unexpected time The code is simply var…
XSL
  • 2,965
  • 7
  • 38
  • 61
25
votes
1 answer

What is the difference between __cause__ and __context__?

These are attributes for Python exceptions, but I am having trouble wrapping my head around them. Python's documentation seems rather quiet about this. I took a look at the documentation but am rather confused. So, what is the difference between the…
Tyler Crompton
  • 12,284
  • 14
  • 65
  • 94
25
votes
3 answers

When would you throw a DomainException in PHP?

I was going through the list of predefined Exceptions in PHP and I noticed the DomainException. Anyone know what does DomainException mean? Does it mean failed data model validation?
oscarkuo
  • 10,431
  • 6
  • 49
  • 62
25
votes
3 answers

symfony2 and throwing exception error

I am trying to throw exceptions and I am doing the following: use Symfony\Component\HttpKernel\Exception\HttpNotFoundException; use Symfony\Component\Security\Core\Exception\AccessDeniedException; I am then using them the following way: throw new…
Strong Like Bull
  • 11,155
  • 36
  • 98
  • 169
25
votes
5 answers

how do you handle and parse JPA persistence exceptions to provide meaningfull message to user

I am fairly new to JPA and want to find best practices when handling persistence exceptions from JPA for things like say, unique constraint violations which can be addressed by the user. There are tons of examples on how to write JPA apps, but…
Bill Rosmus
  • 2,941
  • 7
  • 40
  • 61
24
votes
3 answers

Why raising a tuple works if first element is an Exception?

I have a hard time figuring this one out, it's about mistakes that can be done when raising an exception in Python 2.7: try: raise [1, 2, 3, 4] except Exception as ex: print ex the message here is "exceptions must be old-style classes or…
dahpgjgamgan
  • 2,977
  • 4
  • 25
  • 26
24
votes
1 answer

Can gdb be set to break on any throw?

I am debugging code with exception throwing and exception handling. I would like gdb to break immediately when an exception is thrown, so i can inspect the state of the program and the call stack. How can I make gdb break when any exception is…
zr.
  • 7,528
  • 11
  • 50
  • 84
24
votes
8 answers

How can I set the message on an exception in Java?

I want to set a custom exception message. However, I'm unsure of how to do this. Will I need to create a custom exception class or is there an easier way of doing this?
user843337
24
votes
3 answers

Throwing exceptions in ASP.NET C#

Is there a difference between just saying throw; and throw ex; assuming ex is the exception you're catching?
Chris Westbrook
  • 1,960
  • 5
  • 23
  • 35
24
votes
2 answers

How can I wait on tasks without throwing TaskCanceledExceptions?

I have a method that creates some Tasks, and then waits on them with WaitAll before returning. The problem is, if those tasks got canceled, then WaitAll throws an AggregateException containing lots of TaskCanceledExceptions. That means that WaitAll…
Joe White
  • 94,807
  • 60
  • 220
  • 330
1 2 3
99
100