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
896
votes
15 answers

python exception message capturing

import ftplib import urllib2 import os import logging logger = logging.getLogger('ftpuploader') hdlr = logging.FileHandler('ftplog.log') formatter = logging.Formatter('%(asctime)s %(levelname)s…
Hellnar
  • 62,315
  • 79
  • 204
  • 279
850
votes
11 answers

Can I catch multiple Java exceptions in the same catch clause?

In Java, I want to do something like this: try { ... } catch (/* code to catch IllegalArgumentException, SecurityException, IllegalAccessException, and NoSuchFieldException at the same time */) { someCode(); } ...instead…
froadie
  • 79,995
  • 75
  • 166
  • 235
826
votes
11 answers

Node.js Best Practice Exception Handling

I just started trying out node.js a few days ago. I've realized that the Node is terminated whenever I have an unhandled exception in my program. This is different than the normal server container that I have been exposed to where only the Worker…
momo
  • 21,233
  • 8
  • 39
  • 38
802
votes
21 answers

jQuery Ajax error handling, show custom exception messages

Is there some way I can show custom exception messages as an alert in my jQuery AJAX error message? For example, if I want to throw an exception on the server side via Struts by throw new ApplicationException("User name already exists");, I want to…
None
801
votes
8 answers

Which exception should I raise on bad/illegal argument combinations in Python?

I was wondering about the best practices for indicating invalid argument combinations in Python. I've come across a few situations where you have a function like so: def import_to_orm(name, save=False, recurse=False): """ :param name: Name…
cdleary
  • 69,512
  • 53
  • 163
  • 191
778
votes
23 answers

What is the intended use of the optional "else" clause of the "try" statement in Python?

What is the intended use of the optional else clause of the try statement?
geowa4
  • 40,390
  • 17
  • 88
  • 107
757
votes
21 answers

Understanding checked vs unchecked exceptions in Java

Joshua Bloch in "Effective Java" said that Use checked exceptions for recoverable conditions and runtime exceptions for programming errors (Item 58 in 2nd edition) Let's see if I understand this correctly. Here is my understanding of a…
750
votes
14 answers

How do I properly assert that an exception gets raised in pytest?

Code: # coding=utf-8 import pytest def whatever(): return 9/0 def test_whatever(): try: whatever() except ZeroDivisionError as exc: pytest.fail(exc, pytrace=True) Output: ================================ test session…
Gill Bates
  • 14,330
  • 23
  • 70
  • 138
731
votes
17 answers

How do I log a Python error with debug information?

I am printing Python exception messages to a log file with logging.error: import logging try: 1/0 except ZeroDivisionError as e: logging.error(e) # ERROR:root:division by zero Is it possible to print more detailed information about the…
probably at the beach
  • 14,489
  • 16
  • 75
  • 116
716
votes
4 answers

Correct way to try/except using Python requests module?

try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print(e) Is this correct? Is there a better way to structure this? Will this cover all my bases?
John Smith
  • 11,678
  • 17
  • 46
  • 51
709
votes
9 answers

When should I really use noexcept?

The noexcept keyword can be appropriately applied to many function signatures, but I am unsure as to when I should consider using it in practice. Based on what I have read so far, the last-minute addition of noexcept seems to address some important…
void-pointer
  • 14,247
  • 11
  • 43
  • 61
708
votes
18 answers

Why catch and rethrow an exception in C#?

I'm looking at the article C# - Data Transfer Object on serializable DTOs. The article includes this piece of code: public static string SerializeDTO(DTO dto) { try { XmlSerializer xmlSer = new XmlSerializer(dto.GetType()); …
corlettk
  • 13,288
  • 7
  • 38
  • 52
619
votes
7 answers

Begin, Rescue and Ensure in Ruby?

I've recently started programming in Ruby, and I am looking at exception handling. I was wondering if ensure was the Ruby equivalent of finally in C#? Should I have: file = File.open("myFile.txt", "w") begin file << "#{content} \n" rescue …
Lloyd Powell
  • 18,270
  • 17
  • 87
  • 123
611
votes
13 answers

What is the difference between `throw new Error` and `throw someObject`?

I want to write a common error handler which will catch custom errors thrown on purpose at any instance of the code. When I did throw new Error('sample') like in the following code try { throw new Error({'hehe':'haha'}); // throw new…
Jayapal Chandran
  • 10,600
  • 14
  • 66
  • 91
611
votes
17 answers

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

I have this code: public static String SelectRandomFromTemplate(String template,int count) { String[] split = template.split("|"); List list=Arrays.asList(split); Random r = new Random(); while( list.size() > count ) { …
Pentium10
  • 204,586
  • 122
  • 423
  • 502