# Python Error Handling

The `try` block lets you test a block of code for errors.
The `except` block lets you handle the error.
The `else` block lets you execute code when there is no error.
The `finally` block lets you execute code, regardless of the result of the try- and except blocks.

## Basic Try-Except

```python
try:
    print(x)
except NameError:
    print("Variable x is not defined")
except:
    print("Something else went wrong")
```

## Else

You can use the `else` keyword to define a block of code to be executed if no errors were raised.

```python
try:
    print("Hello")
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")
```

## Finally

The `finally` block, if specified, will be executed regardless if the try block raises an error or not.

```python
try:
    f = open("demofile.txt")
    try:
        f.write("Lorum Ipsum")
    except:
        print("Something went wrong when writing to the file")
    finally:
        f.close()
except:
    print("Something went wrong when opening the file")
```

## Raising Exceptions

As a Python developer you can choose to throw an exception if a condition occurs.

```python
x = -1

if x < 0:
    raise Exception("Sorry, no numbers below zero")
```

## Custom Exceptions

You can define your own exceptions by creating a new class that is derived from the built-in `Exception` class.

```python
class CustomError(Exception):
    pass

try:
    raise CustomError("This is a custom error")
except CustomError as e:
    print(e)
```

[[programming/python/python]]