What happens if except clause is written without any exception type explain with an example?

Exceptions are errors that happen during execution of the program. Python won’t tell you about errors like syntax errors (grammar faults), instead it will abruptly stop.

An abrupt exit is bad for both the end user and developer.

Instead of an emergency halt, you can use a try except statement to properly deal with the problem. An emergency halt will happen if you do not properly handle exceptions.

Related course: Complete Python Programming Course & Exercises

What are exceptions in Python?

Python has built-in exceptions which can output an error. If an error occurs while running the program, it’s called an exception.

If an exception occurs, the type of exception is shown. Exceptions needs to be dealt with or the program will crash. To handle exceptions, the

1
2
3
4
5
6
7 block is used.

Some exceptions you may have seen before are

1
2
3
4
5
6
8,
1
2
3
4
5
6
9 or
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
0 but there are many more.

All exceptions in Python inherit from the class BaseException. If you open the Python interactive shell and type the following statement it will list all built-in exceptions:

 >>> dir(builtins)

The idea of the try-except clause is to handle exceptions (errors at runtime). The syntax of the try-except block is:

1
2
3
4
try:

except Exception:

The idea of the try-except block is this:

  • try: the code with the exception(s) to catch. If an exception is raised, it jumps straight into the except block.

  • except: this code is only executed if an exception occured in the try block. The except block is required with a try block, even if it contains only the pass statement.

It may be combined with the else and finally keywords.

  • else: Code in the else block is only executed if no exceptions were raised in the try block.

  • finally: The code in the finally block is always executed, regardless of if a an exception was raised or not.

Catching Exceptions in Python

The try-except block can handle exceptions. This prevents abrupt exits of the program on error. In the example below we purposely raise an exception.

1
2
3
4
5
6
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')

After the except block, the program continues. Without a try-except block, the last line wouldn’t be reached as the program would crash.

 $ python3 example.py

Divided by zero
Should reach here

In the above example we catch the specific exception ZeroDivisionError. You can handle any exception like this:

1
2
3
4
5
6
try: 
open("fantasy.txt")
except:
print('Something went wrong')

print('Should reach here')

You can write different logic for each type of exception that happens:

1
2
3
4
5
6
7
8
9
10
try: 
# your code here
except FileNotFoundError:
# handle exception
except IsADirectoryError:
# handle exception
except:
# all other types of exceptions

print('Should reach here')

Related course: Complete Python Programming Course & Exercises

try-except

Lets take do a real world example of the try-except block.

The program asks for numeric user input. Instead the user types characters in the input box. The program normally would crash. But with a try-except block it can be handled properly.

The try except statement prevents the program from crashing and properly deals with it.

1
2
3
4
5
6
1
2
3
4
1

Entering invalid input, makes the program continue normally:

What happens if except clause is written without any exception type explain with an example?

The try except statement can be extended with the finally keyword, this will be executed if no exception is thrown:

1
2
3
4
2
1
2
3
4
3

The program continues execution if no exception has been thrown.

There are different kinds of exceptions: ZeroDivisionError, NameError, TypeError and so on. Sometimes modules define their own exceptions.

The try-except block works for function calls too:

1
2
3
4
4
1
2
3
4
5

This outputs:

1
2
3
4
6

If you are a beginner, then I highly recommend this book.

try finally

A try-except block can have the finally clause (optionally). The finally clause is always executed.
So the general idea is:

1
2
3
4
5
6
1
2
3
4
8

For instance: if you open a file you’ll want to close it, you can do so in the finally clause.

1
2
3
4
9
try:

except Exception:

0

try else

The else clause is executed if and only if no exception is raised. This is different from the finally clause that’s always executed.

1
2
3
4
9
try:

except Exception:

2

Output:

try:

except Exception:

3

You can catch many types of exceptions this way, where the else clause is executed only if no exception happens.

try:

except Exception:

4
try:

except Exception:

5

Raise Exception

Exceptions are raised when an error occurs. But in Python you can also force an exception to occur with the keyword

try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
1.

Any type of exception can be raised:

1
2
3
4
try:

except Exception:

7
try:

except Exception:

8
try:

except Exception:

9

Related course: Complete Python Programming Course & Exercises

Built-in exceptions

A list of Python's Built-in Exceptions is shown below. This list shows the Exception and why it is thrown (raised).

ExceptionCause of ErrorAssertionErrorif
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
2 statement fails.AttributeErrorif attribute assignment or reference fails.EOFErrorif the
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
3 functions hits end-of-file condition.FloatingPointErrorif a floating point operation fails.GeneratorExitRaise if a generator's
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
4 method is called.ImportErrorif the imported module is not found.IndexErrorif index of a sequence is out of range.KeyErrorif a key is not found in a dictionary.KeyboardInterruptif the user hits interrupt key (Ctrl+c or delete).MemoryErrorif an operation runs out of memory.NameErrorif a variable is not found in local or global scope.NotImplementedErrorby abstract methods.OSErrorif system operation causes system related error.OverflowErrorif result of an arithmetic operation is too large to be represented.ReferenceErrorif a weak reference proxy is used to access a garbage collected referent.RuntimeErrorif an error does not fall under any other category.StopIterationby
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
5 function to indicate that there is no further item to be returned by iterator.SyntaxErrorby parser if syntax error is encountered.IndentationErrorif there is incorrect indentation.TabErrorif indentation consists of inconsistent tabs and spaces.SystemErrorif interpreter detects internal error.SystemExitby
try: 
1 / 0
except ZeroDivisionError:
print('Divided by zero')

print('Should reach here')
6 function.TypeErrorif a function or operation is applied to an object of incorrect type.UnboundLocalErrorif a reference is made to a local variable in a function or method, but no value has been bound to that variable.UnicodeErrorif a Unicode-related encoding or decoding error occurs.UnicodeEncodeErrorif a Unicode-related error occurs during encoding.UnicodeDecodeErrorif a Unicode-related error occurs during decoding.UnicodeTranslateErrorif a Unicode-related error occurs during translating.ValueErrorif a function gets argument of correct type but improper value.ZeroDivisionErrorif second operand of division or modulo operation is zero.User-defined Exceptions

Python has many standard types of exceptions, but they may not always serve your purpose.
Your program can have your own type of exceptions.

To create a user-defined exception, you have to create a class that inherits from Exception.

1
2
3
4
1
2
3
4
5
6
1

You made a user-defined exception named LunchError in the above code. You can raise this new exception if an error occurs.

Outputs your custom error:

1
2
3
4
5
6
2

Your program can have many user-defined exceptions. The program below throws exceptions based on a new projects money:

1
2
3
4
5
6
3
1
2
3
4
5
6
4

Here are some sample runs:

1
2
3
4
5
6
5

1
2
3
4
5
6
6

It is a good practice to put all user-defined exceptions in a separate file (exceptions.py or errors.py). This is common practice in standard modules too.

What is exception handling in Python explain with example?

An exception in Python is an incident that happens while executing a program that causes the regular course of the program's commands to be disrupted. When a Python code comes across a condition it can't handle, it raises an exception. An object in Python that describes an error is called an exception.

How can the try

A Try-Except statement is a code block that allows your program to take alternative actions in case an error occurs. Python will first attempt to execute the code in the try statement (code block 1). If no exception occurs, the except statement is skipped and the execution of the try statement is finished.

What are the types of exceptions in Python?

Built-in Exceptions.

Why exception handling is needed in Python?

Exception handling allows you to separate error-handling code from normal code. An exception is a Python object which represents an error. As with code comments, exceptions helps you to remind yourself of what the program expects. It clarifies the code and enhances readability.