Exception: Difference between revisions
CSV import Tags: mobile edit mobile web edit |
CSV import |
||
| Line 61: | Line 61: | ||
{{Computer-programming-stub}} | {{Computer-programming-stub}} | ||
{{No image}} | |||
Revision as of 16:57, 10 February 2025
Exception
An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. In many programming languages, exceptions are used to handle errors and other exceptional events. Exceptions provide a way to transfer control from one part of a program to another.
Types of Exceptions
Exceptions can be broadly classified into two categories:
- Checked exceptions: These are exceptions that a well-written application should anticipate and recover from. They are checked at compile-time.
- Unchecked exceptions: These are exceptions that are not checked at compile-time. They are usually the result of programming errors, such as logic mistakes or improper use of an API.
Exception Handling
Exception handling is a construct in some programming languages to handle or deal with errors automatically. The main idea is to separate the error-handling code from the regular code. This is typically done using the following keywords:
- try: A block of code that is attempted.
- catch: A block of code that handles the exception if one occurs.
- finally: A block of code that is always executed after the try block, regardless of whether an exception was thrown or not.
- throw: Used to signal the occurrence of an exception.
Exception Propagation
When an exception is thrown, it propagates up the call stack until it is caught by an appropriate exception handler. If no handler is found, the program may terminate.
Common Exceptions in Programming Languages
Different programming languages have their own sets of common exceptions. For example:
- In Java:
* NullPointerException * ArrayIndexOutOfBoundsException * IOException
- In Python:
* IndexError * KeyError * ValueError
Best Practices
- Always catch the most specific exception first.
- Avoid catching generic exceptions unless absolutely necessary.
- Clean up resources in a finally block or use a try-with-resources statement.
- Log exceptions appropriately to aid in debugging.
See Also
Related Pages

This article is a computer programming stub. You can help WikiMD by expanding it!