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. Show
Free PDF Download: Python 3 Cheat Sheet Exceptions versus Syntax ErrorsSyntax errors occur when the parser detects an incorrect statement. Observe the following example:
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:
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 6, Python details what type of exception error was encountered. In this case, it was a 7. Python comes with various built-in exceptions as well as the possibility to create self-defined exceptions.Remove adsRaising an ExceptionWe can use 8 to throw an exception if a condition occurs. The statement can be complemented with a custom exception.If you want to throw an error when a certain condition occurs using 8, you could go about it like this:
When you run this code, the output will be the following:
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 ExceptionInstead of waiting for a program to crash midway, you can also start by making an assertion in Python. We 1 that a certain condition is met. If this condition turns out to be 2, then that is excellent! The program can continue. If the condition turns out to be 3, you can have the program throw an 0 exception.Have a look at the following example, where it is asserted that the code will be executed on a Linux system:
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 3 and the result would be the following:
In this example, throwing an 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 ExceptionsThe 7 and 8 block in Python is used to catch and handle exceptions. Python executes code following the 7 statement as a “normal” part of the program. The code that follows the 8 statement is the program’s response to any exceptions in the preceding 7 clause.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 8 clause determines how your program responds to exceptions.The following function can help you understand the 7 and 8 block:
The 7 can only run on a Linux system. The 1 in this function will throw an 0 exception if you call it on an operating system other then Linux.You can give the function a 7 using the following code:
The way you handled the error here is by handing out a 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 1 into something that would generate an informative message, like so:
Execute this code on a Windows machine: 0When 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 0 and output that message to screen: 1Running this function on a Windows machine outputs the following: 2The first message is the 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 0 exception and printed it to screen.Here’s another example where you open a file and use a built-in exception: 3If file.log does not exist, this block of code will output the following: 4This 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:
To catch this type of exception and print it to screen, you could use the following code: 5In this case, if file.log does not exist, the output will be the following: 6You can have more than one function call in your 7 clause and anticipate catching various exceptions. A thing to note here is that the code in the 7 clause will stop as soon as an exception is encountered.Warning: Catching 9 hides all errors…even those which are completely unexpected. This is why you should avoid bare 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 7 function and then try to open a file: 7If the file does not exist, running this code on a Windows machine will output the following: 8Inside the 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: 6Here are the key takeaways:
The def linux_interaction(): assert ('linux' in sys.platform), "Function can only run on Linux systems." print('Doing something.') 6 ClauseIn Python, using the 6 statement, you can instruct a program to execute a certain block of code only in the absence of exceptions.Look at the following example: 0If you were to run this code on a Linux system, the output would be the following: 1Because the program did not run into any exceptions, the 6 clause was executed.You can also 7 to run code inside the 6 clause and catch possible exceptions there as well: 2If you were to execute this code on a Linux machine, you would get the following result: 3From the output, you can see that the 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 6 exception.Cleaning Up After Using try: linux_interaction() except: pass 3Imagine 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 3 clause.Have a look at the following example: 4In the previous code, everything in the 3 clause will be executed. It does not matter if you encounter an exception somewhere in the 7 or 6 clauses. Running the previous code on a Windows machine would output the following: 5Summing UpAfter 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:
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. Send Me Python Tricks » About Said van de Klundert Said is a network engineer, Python enthusiast, and a guest author at Real Python. » More about SaidEach 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: Adriana 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 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 EmailWhat’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. /. |