Cara menggunakan python throw exception up

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In this article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

Cara menggunakan python throw exception up

Free PDF Download: Python 3 Cheat Sheet

Exceptions versus Syntax Errors

Syntax errors occur when the parser detects an incorrect statement. Observe the following example:

>>> print( 0 / 0 ))
  File "<stdin>", line 1
    print( 0 / 0 ))
                  ^
SyntaxError: invalid syntax

The arrow indicates where the parser ran into the syntax error. In this example, there was one bracket too many. Remove it and run your code again:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

This time, you ran into an exception error. This type of error occurs whenever syntactically correct Python code results in an error. The last line of the message indicated what type of exception error you ran into.

Instead of showing the message

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
6, Python details what type of exception error was encountered. In this case, it was a
x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
7. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.

Remove ads

Raising an Exception

We can use

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
8 to throw an exception if a condition occurs. The statement can be complemented with a custom exception.

Cara menggunakan python throw exception up

If you want to throw an error when a certain condition occurs using

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
8, you could go about it like this:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))

When you run this code, the output will be the following:

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10

The program comes to a halt and displays our exception to screen, offering clues about what went wrong.

The Traceback (most recent call last): File "<input>", line 4, in <module> Exception: x should not exceed 5. The value of x was: 10 0 Exception

Instead of waiting for a program to crash midway, you can also start by making an assertion in Python. We

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
1 that a certain condition is met. If this condition turns out to be
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
2, then that is excellent! The program can continue. If the condition turns out to be
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
3, you can have the program throw an
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0 exception.

Cara menggunakan python throw exception up

Have a look at the following example, where it is asserted that the code will be executed on a Linux system:

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."

If you run this code on a Linux machine, the assertion passes. If you were to run this code on a Windows machine, the outcome of the assertion would be

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
3 and the result would be the following:

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.

In this example, throwing an

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0 exception is the last thing that the program will do. The program will come to halt and will not continue. What if that is not what you want?

The Traceback (most recent call last): File "<input>", line 4, in <module> Exception: x should not exceed 5. The value of x was: 10 7 and Traceback (most recent call last): File "<input>", line 4, in <module> Exception: x should not exceed 5. The value of x was: 10 8 Block: Handling Exceptions

The

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 and
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
8 block in Python is used to catch and handle exceptions. Python executes code following the
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 statement as a “normal” part of the program. The code that follows the
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
8 statement is the program’s response to any exceptions in the preceding
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 clause.

Cara menggunakan python throw exception up

As you saw earlier, when syntactically correct code runs into an error, Python will throw an exception error. This exception error will crash the program if it is unhandled. The

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
8 clause determines how your program responds to exceptions.

The following function can help you understand the

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 and
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
8 block:

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')

The

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
7 can only run on a Linux system. The
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
1 in this function will throw an
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0 exception if you call it on an operating system other then Linux.

You can give the function a

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 using the following code:

try:
    linux_interaction()
except:
    pass

The way you handled the error here is by handing out a

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
1. If you were to run this code on a Windows machine, you would get the following output:


You got nothing. The good thing here is that the program did not crash. But it would be nice to see if some type of exception occurred whenever you ran your code. To this end, you can change the

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
1 into something that would generate an informative message, like so:

try:
    linux_interaction()
except:
    print('Linux function was not executed')

Execute this code on a Windows machine:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
0

When an exception occurs in a program running this function, the program will continue as well as inform you about the fact that the function call was not successful.

What you did not get to see was the type of error that was thrown as a result of the function call. In order to see exactly what went wrong, you would need to catch the error that the function threw.

The following code is an example where you capture the

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0 and output that message to screen:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
1

Running this function on a Windows machine outputs the following:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
2

The first message is the

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0, informing you that the function can only be executed on a Linux machine. The second message tells you which function was not executed.

In the previous example, you called a function that you wrote yourself. When you executed the function, you caught the

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
0 exception and printed it to screen.

Here’s another example where you open a file and use a built-in exception:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
3

If file.log does not exist, this block of code will output the following:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
4

This is an informative message, and our program will still continue to run. In the Python docs, you can see that there are a lot of built-in exceptions that you can use here. One exception described on that page is the following:

Exception

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
6

Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.

To catch this type of exception and print it to screen, you could use the following code:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
5

In this case, if file.log does not exist, the output will be the following:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
6

You can have more than one function call in your

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 clause and anticipate catching various exceptions. A thing to note here is that the code in the
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 clause will stop as soon as an exception is encountered.

Warning: Catching

Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
9 hides all errors…even those which are completely unexpected. This is why you should avoid bare
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
8 clauses in your Python programs. Instead, you’ll want to refer to specific exception classes you want to catch and handle. You can learn more about why this is a good idea in this tutorial.

Look at the following code. Here, you first call the

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
7 function and then try to open a file:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
7

If the file does not exist, running this code on a Windows machine will output the following:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
8

Inside the

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 clause, you ran into an exception immediately and did not get to the part where you attempt to open file.log. Now look at what happens when you run the code on a Linux machine:

>>> print( 0 / 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
6

Here are the key takeaways:

  • A
    Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    7 clause is executed up until the point where the first exception is encountered.
  • Inside the
    Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    8 clause, or the exception handler, you determine how the program responds to the exception.
  • You can anticipate multiple exceptions and differentiate how the program should respond to them.
  • Avoid using bare
    Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    8 clauses.

Remove ads

The def linux_interaction(): assert ('linux' in sys.platform), "Function can only run on Linux systems." print('Doing something.') 6 Clause

In Python, using the

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')
6 statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.

Cara menggunakan python throw exception up

Look at the following example:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
0

If you were to run this code on a Linux system, the output would be the following:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
1

Because the program did not run into any exceptions, the

def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')
6 clause was executed.

You can also

Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 to run code inside the
def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')
6 clause and catch possible exceptions there as well:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
2

If you were to execute this code on a Linux machine, you would get the following result:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
3

From the output, you can see that the

import sys
assert ('linux' in sys.platform), "This code runs on Linux only."
7 function ran. Because no exceptions were encountered, an attempt to open file.log was made. That file did not exist, and instead of opening the file, you caught the
Traceback (most recent call last):
  File "<input>", line 2, in <module>
AssertionError: This code runs on Linux only.
6 exception.

Cleaning Up After Using try: linux_interaction() except: pass 3

Imagine that you always had to implement some sort of action to clean up after executing your code. Python enables you to do so using the

try:
    linux_interaction()
except:
    pass
3 clause.

Cara menggunakan python throw exception up

Have a look at the following example:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
4

In the previous code, everything in the

try:
    linux_interaction()
except:
    pass
3 clause will be executed. It does not matter if you encounter an exception somewhere in the
Traceback (most recent call last):
  File "<input>", line 4, in <module>
Exception: x should not exceed 5. The value of x was: 10
7 or
def linux_interaction():
    assert ('linux' in sys.platform), "Function can only run on Linux systems."
    print('Doing something.')
6 clauses. Running the previous code on a Windows machine would output the following:

x = 10
if x > 5:
    raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
5

Remove ads

Summing Up

After seeing the difference between syntax errors and exceptions, you learned about various ways to raise, catch, and handle exceptions in Python. In this article, you saw the following options:

  • x = 10
    if x > 5:
        raise Exception('x should not exceed 5. The value of x was: {}'.format(x))
    
    8 allows you to throw an exception at any time.
  • Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    1 enables you to verify if a certain condition is met and throw an exception if it isn’t.
  • In the
    Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    7 clause, all statements are executed until an exception is encountered.
  • Traceback (most recent call last):
      File "<input>", line 4, in <module>
    Exception: x should not exceed 5. The value of x was: 10
    
    8 is used to catch and handle the exception(s) that are encountered in the try clause.
  • def linux_interaction():
        assert ('linux' in sys.platform), "Function can only run on Linux systems."
        print('Doing something.')
    
    6 lets you code sections that should run only when no exceptions are encountered in the try clause.
  • try:
        linux_interaction()
    except:
        pass
    
    3 enables you to execute sections of code that should always run, with or without any previously encountered exceptions.

Free PDF Download: Python 3 Cheat Sheet

Hopefully, this article helped you understand the basic tools that Python has to offer when dealing with exceptions.

Mark as Completed

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Raising and Handling Python Exceptions

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Cara menggunakan python throw exception up

Send Me Python Tricks »

About Said van de Klundert

Cara menggunakan python throw exception up
Cara menggunakan python throw exception up

Said is a network engineer, Python enthusiast, and a guest author at Real Python.

» More about Said


Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Cara menggunakan python throw exception up

Adriana

Cara menggunakan python throw exception up

Joanna

Master Real-World Python Skills With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

Tweet Share Share Email

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. and get answers to common questions in our support portal.

Apa itu Exception pada python?

Exception adalah objek Python yang mewakili kesalahan.

Apa penyebab terjadinya suatu pengecualian exceptions di suatu program?

Exception dipicu oleh runtime error, yaitu error atau kesalahan yang terjadi saat program dieksekusi oleh interpreter.

Pembagian dengan nol adalah contoh jenis kesalahan apa pada python?

6. Arithmetic Error Sebagai contoh, ketika kamu meminta komputer untuk melakukan pembagian dengan angka 0 (nol).

Bagaimana cara membuat penanganan kesalahan error handling yang baik pada program?

Cara Membuat Error Handling yang Baik.
Gunakan bahasa yang mudah dipahami oleh user..
Hindari kata-kata seperti : bad,dummy, dll..
Hindari kalimat perintah..
FAQ (Frequently Asked Questions)..
Optimalisasikan dan pemanfaatan undo redo function dan cancel..
Menyiapkan berbagai macam model respon..
Validitas masukan. /.