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
607
votes
6 answers

Is there anything like .NET's NotImplementedException in Java?

Is there anything like .NET's NotImplementedException in Java?
devoured elysium
  • 101,373
  • 131
  • 340
  • 557
605
votes
12 answers

Get exception description and stack trace which caused an exception, all as a string

How to convert a caught Exception (its description and stack trace) into a str for external use? try: method_that_can_raise_an_exception(params) except Exception as e: print(complete_exception_description(e))
bluish
  • 26,356
  • 27
  • 122
  • 180
603
votes
17 answers

Uncatchable ChuckNorrisException

Is it possible to construct a snippet of code in Java that would make a hypothetical java.lang.ChuckNorrisException uncatchable? Thoughts that came to mind are using for example interceptors or aspect-oriented programming.
Max Charas
  • 4,980
  • 3
  • 20
  • 40
593
votes
4 answers

Mockito test a void method throws an exception

I have a method with a void return type. It can also throw a number of exceptions so I'd like to test those exceptions being thrown. All attempts have failed with the same reason: The method when(T) in the type Stubber is not applicable for the…
edwardmlyte
  • 15,937
  • 23
  • 58
  • 83
572
votes
26 answers

IllegalArgumentException or NullPointerException for a null parameter?

I have a simple setter method for a property and null is not appropriate for this particular property. I have always been torn in this situation: should I throw an IllegalArgumentException, or a NullPointerException? From the javadocs, both seem…
Mike Stone
  • 44,224
  • 30
  • 113
  • 140
567
votes
4 answers

Python: How to ignore an exception and proceed?

I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do…
The.Anti.9
  • 43,474
  • 48
  • 123
  • 161
560
votes
13 answers

How to add manifest permission to an application?

I am trying to access HTTP link using HttpURLConnection in Android to download a file, but I am getting this warning in LogCat: WARN/System.err(223): java.net.SocketException: Permission denied (maybe missing INTERNET permission) I have added…
rob
  • 5,771
  • 4
  • 23
  • 26
559
votes
11 answers

Is it a good practice to use try-except-else in Python?

From time to time in Python, I see the block: try: try_this(whatever) except SomeException as exception: #Handle exception else: return something What is the reason for the try-except-else to exist? I do not like that kind of programming,…
Juan Antonio Gomez Moriano
  • 13,103
  • 10
  • 47
  • 65
557
votes
18 answers

What are the effects of exceptions on performance in Java?

Question: Is exception handling in Java actually slow? Conventional wisdom, as well as a lot of Google results, says that exceptional logic shouldn't be used for normal program flow in Java. Two reasons are usually given, it is really slow - even…
John Ellinwood
  • 14,291
  • 7
  • 38
  • 48
550
votes
36 answers

Should a retrieval method return 'null' or throw an exception when it can't produce the return value?

I am using java language,I have a method that is supposed to return an object if it is found. If it is not found, should I: return null throw an exception other Which is the best practise or idiom?
Robert Deml
  • 12,390
  • 20
  • 65
  • 92
548
votes
13 answers

Is there a difference between "throw" and "throw ex"?

There are some posts that asks what the difference between those two are already. (why do I have to even mention this...) But my question is different in a way that I am calling "throw ex" in another error god-like handling method. public class…
dance2die
  • 35,807
  • 39
  • 131
  • 194
540
votes
9 answers

What is the proper way to rethrow an exception in C#?

Is it better to do this: try { ... } catch (Exception ex) { ... throw; } Or this: try { ... } catch (Exception ex) { ... throw ex; } Do they do the same thing? Is one better than the other?
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
528
votes
33 answers

The case against checked exceptions

For a number of years now I have been unable to get a decent answer to the following question: why are some developers so against checked exceptions? I have had numerous conversations, read things on blogs, read what Bruce Eckel had to say (the…
TofuBeer
  • 60,850
  • 18
  • 118
  • 163
527
votes
15 answers

What is a StackOverflowError?

What is a StackOverflowError, what causes it, and how should I deal with them?
Ziggy
  • 21,845
  • 28
  • 75
  • 104
527
votes
18 answers

Why do we need the "finally" clause in Python?

I am not sure why we need finally in try...except...finally statements. In my opinion, this code block try: run_code1() except TypeError: run_code2() other_code() is the same with this one using finally: try: run_code1() except…
RNA
  • 146,987
  • 15
  • 52
  • 70