Solution oriented error handling
This is a modal window.
The media could not be loaded, either because the server or network failed or because the format is not supported.
Formal Metadata
Title |
| |
Title of Series | ||
Part Number | 11 | |
Number of Parts | 119 | |
Author | ||
License | CC Attribution 3.0 Unported: You are free to use, adapt and copy, distribute and transmit the work or content in adapted or unchanged form for any legal purpose as long as the work is attributed to the author in the manner specified by the author or licensor. | |
Identifiers | 10.5446/20039 (DOI) | |
Publisher | ||
Release Date | ||
Language | ||
Production Place | Berlin |
Content Metadata
Subject Area | ||
Genre | ||
Abstract |
| |
Keywords |
EuroPython 201411 / 119
1
2
9
10
11
13
15
17
22
23
24
27
28
41
44
46
49
56
78
79
80
81
84
97
98
99
101
102
104
105
107
109
110
111
112
113
116
118
119
00:00
CodeUsabilitySet (mathematics)Mechanism designComputer animationLecture/Conference
00:27
Library (computing)Standard deviationFocus (optics)CodeFormal languageMechanism designException handlingMessage passingCodeMechanism designResultantExtension (kinesiology)Library (computing)Online helpException handlingError messageComputer animation
00:51
CodeUsabilityInformationCodeError messageMessage passingLecture/Conference
01:13
Exception handlingHierarchyMessage passingError messageException handlingHierarchySheaf (mathematics)Computer animation
01:39
Computer programCondition numberCodeResultantAreaComputer programmingCondition numberContext awarenessLecture/ConferenceComputer animation
02:06
Exception handlingPhysical systemResultantComputer programmingComputer animationLecture/Conference
02:56
Computer programoutputRange (statistics)Integrated development environmentOperator (mathematics)Personal digital assistantFile formatMiniDiscSoftware developerWritingCAN busoutputComputer programmingIntegrated development environmentResultantCodeOperator (mathematics)Computer animation
03:49
SoftwareIntegrated development environmentResultantoutputComputer programmingRight angleRange (statistics)Operator (mathematics)CASE <Informatik>WordMiniDiscLecture/Conference
04:19
InformationComputer programCASE <Informatik>Computer programmingIntegrated development environmentoutputResultantSemiconductor memoryInformationRight angleComputer animationLecture/Conference
04:59
InformationSoftware developerComputer programInformationWaveException handlingComputer animationLecture/Conference
05:23
Standard deviationException handlingStandard deviationVariable (mathematics)Library (computing)Exception handlingRepresentation (politics)Computer programmingState of matterProgrammer (hardware)Computer animationLecture/Conference
06:06
Computer programDataflowCondition numberMountain passInformationCodeException handlingException handlingMessage passingTouchscreenCondition numberInheritance (object-oriented programming)CASE <Informatik>Error messageType theoryParameter (computer programming)Computer animation
06:50
CASE <Informatik>ResultantMechanism designComputer fileCASE <Informatik>Lecture/ConferenceComputer animation
07:15
Social classMereologyContext awarenessStatement (computer science)CoroutineObject (grammar)Read-only memoryCursor (computers)Letterpress printingRow (database)ImplementationResource allocationExecution unitFunction (mathematics)Interior (topology)Software bugArtificial neural networkTask (computing)Data typeStatement (computer science)Computer fileIndependence (probability theory)Context awarenessSocial classBitResultantSource codeMereologyData managementTask (computing)Reading (process)Order (biology)Water vaporObject (grammar)CoroutineCASE <Informatik>Different (Kate Ryan album)Internet service providerStandard deviationRadiusDataflowLine (geometry)CodeLecture/ConferenceMeeting/InterviewComputer animation
09:18
Computer fileContext awarenessContext awarenessCodeData managementLine (geometry)ResultantFerry CorstenMereologySocial classFunctional (mathematics)System callVariable (mathematics)Object (grammar)Lecture/ConferenceComputer animation
09:53
Lie groupContext awarenessInterior (topology)Dean numberLevel (video gaming)WeightVarianceContext awarenessData managementComputer fileCASE <Informatik>CoroutineSource codeSound effectEndliche ModelltheorieReading (process)Lecture/ConferenceComputer animation
10:38
Vector spaceStatement (computer science)Table (information)Lecture/Conference
11:11
Sound effectComputer programCASE <Informatik>Condition numberFunction (mathematics)Context awarenessCondition numberComputer programmingConsistencyError messageDigitizingSound effectMultilaterationFunctional (mathematics)Exception handlingDifferent (Kate Ryan album)CASE <Informatik>Bit rateExtension (kinesiology)Arrow of timeEndliche ModelltheorieMessage passingEvent horizonCircleRadiusSpeech synthesisComputer animation
12:28
Context awarenessSubsetException handlingMereologyData managementContext awarenessLecture/Conference
12:51
Software developerOperator (mathematics)CodeMessage passingLatent heatFocus (optics)Condition numberDependent and independent variablesLatent heatError messageOperator (mathematics)Condition numberCodeComputer animationLecture/ConferenceMeeting/Interview
13:20
outputIntegrated development environmentComputer programRaw image formatSemiconductor memoryComputer programmingIntegrated development environmentoutputDependent and independent variablesRight angleOperator (mathematics)ResultantComputer animationDiagram
13:56
Parameter (computer programming)Software developerComputer programmingInformationWebsiteResultantDependent and independent variablesCircleLecture/ConferenceMeeting/Interview
14:29
CoroutineState of matterComputer programSoftware developerCodeParameter (computer programming)Message passingComputer programmingCodeSoftware bugState of matterCuboidPhase transitionInsertion lossComputer animation
15:02
Parameter (computer programming)Software developerIntegrated development environmentParameter (computer programming)PreconditionerPoint (geometry)Operator (mathematics)Validity (statistics)Dependent and independent variablesCoroutineMultiplication signSystem callVarianceWritingComputer programmingLecture/Conference
15:54
Software developerCondition numberIntegrated development environmentOperations researchSpacetimeComputer networkMiniDiscLaceMultiplication signInternet service provideroutputMiniDiscIntegrated development environmentSpacetimeSemiconductor memoryCondition numberSoftwareComputer programmingArray data structureMessage passingGroup actionUsabilityState of matterError messageOperator (mathematics)EntropiecodierungVideo gameWordContext awarenessTerm (mathematics)Constructor (object-oriented programming)CodeComputer animationLecture/Conference
17:10
Software developerUsabilityState of matterModal logicGroup actionMessage passingTerm (mathematics)Message passingArrow of timeCodeGroup actionArray data structureOrder (biology)Interface (computing)PlanningComputer animation
17:47
ClefWindowFile formatTime domainSheaf (mathematics)Error messageCondition numberComputer programmingDataflowMatching (graph theory)Computer fileSheaf (mathematics)Configuration spaceLecture/ConferenceMeeting/InterviewComputer animation
18:20
Form (programming)Term (mathematics)Graphical user interfaceGroup actionProcess (computing)Numbering schemeComputer fileLine (geometry)Group actionCondition numberCASE <Informatik>Statement (computer science)Message passingError messageInitial value problemContext awarenessLecture/ConferenceComputer animation
19:01
Form (programming)SoftwareField (computer science)InformationError messageGroup actionTerm (mathematics)Context awarenessForm (programming)Computer fileProcess (computing)CoroutineLecture/Conference
19:47
CoroutineMountain passCASE <Informatik>Function (mathematics)Process (computing)Line (geometry)SineNumbering schemeNumbering schemeLine (geometry)Parameter (computer programming)IntegerError messageException handlingProcess (computing)Bound stateCASE <Informatik>Computer fileData conversionRange (statistics)Function (mathematics)Variable (mathematics)Computer animation
20:45
Group actionMessage passingPattern languageException handlingHierarchyUltraviolet photoelectron spectroscopyLibrary (computing)Social classError messagePattern languageCodeGroup actionUniform resource locatorException handlingHierarchySocial classSimilarity (geometry)WordLecture/ConferenceComputer animation
21:22
Software developerLatent heatLatent heatOperator (mathematics)Exception handlingTask (computing)Dependent and independent variablesPoint (geometry)Lecture/Conference
21:49
Exception handlingCodeoutputException handlingSubject indexingArrow of timeState of matterComputer animationLecture/Conference
22:17
Social classMountain passMessage passingGroup actionLine (geometry)Process (computing)Exception handlingNumbering schemeChainingComplete metric spaceCausalitySoftware developerHierarchyDew pointHierarchyAreaException handlingMessage passingService (economics)Wave packetChainComputer animation
22:48
Default (computer science)Mathematical singularityState of matterGroup actionPattern languageMathematicsException handlingData conversionGraphical user interfaceSubsetBit rateGroup actionOperator (mathematics)Error messageException handlingCartesian coordinate systemPhase transitionForm (programming)Lecture/ConferenceComputer animation
23:22
Mathematical singularityDefault (computer science)State of matterSineInternet service providerDefault (computer science)Validity (statistics)BitCondition numberException handlingRight angleState of matterDependent and independent variablesLecture/Conference
23:56
Software developerCodeMereologyException handlingException handlingOperator (mathematics)CodeCoroutineEndliche ModelltheorieResultantMultiplication signCore dumpSet (mathematics)Computer animation
24:21
CodeException handlingMereologyResultantCodeMoment (mathematics)AreaLecture/Conference
24:49
CodeComputer programCondition numberCASE <Informatik>Group actionFunction (mathematics)CoroutineAreaCondition numberFunctional (mathematics)CoroutineSystem callCodeResultantTemplate (C++)CASE <Informatik>Local area networkCartesian coordinate systemComputer animationLecture/Conference
25:26
CodeNewton's law of universal gravitationMachine codeEmulatorSet (mathematics)Line (geometry)Software developerSummierbarkeitArmArtificial neural networkComputer clusterExplosionMagneto-optical driveArc (geometry)Link (knot theory)Key (cryptography)Exception handlingMetropolitan area networkStatement (computer science)Tracing (software)MereologyUniversal product codeCartesian coordinate systemException handlingResultantComputer animation
25:57
Trigonometric functionsIntegrated development environmentSet (mathematics)Exception handlingCore dumpContext awarenessRun time (program lifecycle phase)Software developerComputer programImplementationCodeFerry CorstenException handlingSet (mathematics)Axiom of choiceRun time (program lifecycle phase)Core dumpLecture/ConferenceComputer animation
26:21
Exception handlingComputer programIntegrated development environmentWorkstation <Musikinstrument>Context awarenessMessage passingResultantData managementStatement (computer science)CASE <Informatik>Exception handlingImplementationCodeContext awarenessCondition numberInsertion lossLecture/Conference
26:49
CodePattern languageMessage passingException handlingValue-added networkVarianceSubsetUniform resource locatorMultiplication signException handlingOnline helpError messagePattern languageGroup actionMetaprogrammierungPoint (geometry)Arithmetic meanLevel (video gaming)Computer animation
28:14
Googol
Transcript: English(auto-generated)
00:15
Thank you, and hello and welcome to my talk about solution-oriented error handling,
00:21
which is a set of simple set of guidelines to use the mechanisms of Python for an efficient way of error handling. It does work with the standard libraries. You don't need any extensions. It yields a small amount of dedicated error handling code,
00:42
and most of your code can focus on producing the results, on producing the stuff your users actually want. It yields helpful error messages that are easy to derive from the code, and it consequently simplifies support in a way that users might be able to deal with more errors
01:01
themselves without opening tickets. Or even if you get a ticket and the error messages in the ticket, you get more information and better information to fix it yourself and support the user. What I'm talking about now is I give a short introduction about errors in general. Then I give an overview of errors in Python.
01:22
How does Python represent errors with exception handling? How does Python clean up resources after errors? Then I'm going to focus on the principles of solution-oriented error handling with dedicated sections on error messages and error hierarchies or exception hierarchies. And I'm summarizing the whole thing
01:41
at the end with a couple of recommendations and guidelines you can apply to your code. So about errors, what are errors? Errors, in the context I'm talking about, are conditions that prevent a program from producing the desired result. So where do errors come from?
02:05
That was a user error. Oh, it quit. That's bad. Yeah. They don't have any error handling or no proper error.
02:23
No, that was system error handling. So I don't know what's wrong. I don't know what to report now. All I can do is restart it. OK. So at least it could recover from the error.
02:43
And now it's talking German to you, which is inefficient. And here we go. We have a program that's supposed to produce a result. Where does the program come from? The program comes from you, the developer.
03:02
You write the program. You code it. But you usually don't code it for yourself. You code it for a user who wants the result. That's why he comes to you. He says, I want something useful. Please make it for me. However, the user usually doesn't only want to program. He wants to provide input.
03:21
And the program should create the result depending on his input. Additionally to that, you need an environment for the program to run in. And the environment sometimes is provided by users. Sometimes it's provided by dedicated people. We usually call operations.
03:40
So that's the whole thing we do, basically. So how can errors creep into the whole concept? Well, the users can provide broken input. You might use invalid date formats. They might use values out of range. Operators can provide insufficient environment where there are access rights missing,
04:01
where you cannot connect to a network, where a disk is full. And developers can write the program that is broken, in the sense that it misses corner cases, that it has incorrect results, or as we've just seen, that has insufficient error handling, like LibreOffice. So how do errors get fixed?
04:21
Well, in case of LibreOffice, if this ever gets fixed, somebody will sit down and write a better program. So it's pretty much the same with input data and the environment. Errors get fixed by people. They add more memory. They add valid, or they change the input data so that they are valid. After that, the program can continue and finally
04:40
produce the desired result. But for people to actually fix errors, they need information. And ideally, the program provides this information, which LibreOffice didn't. Actually, ideally, the developer writes the program in a way so that it
05:02
provides this information. And this is what this talk is about. Solution-oriented error handling is a way to make it easier for you to provide the information to fix errors. OK, errors in Python.
05:22
The widely used way to represent errors are exceptions. You can do funny values. You can do global variables. But essentially and consistently, the standard library uses exceptions to represent errors. And I encourage you to do the same. The major benefit of exceptions is that they cannot be
05:42
ignored accidentally. You don't have to check, is there an error. Once an exception is raised, it just reverses up the calling stack until some routine decides to deal with the error. The Python program cannot simply continue after an error already occurred.
06:00
In C, this is pretty simple. So how do you detect errors? Well, you use an if. And the error condition, and if the condition is true, you know you have an error. And then you just raise an exception. Here's a trivial example. I have a height parameter.
06:20
And if it's less than 0 or it is 0, the exception tells me that the height must be greater than 0. What can I do once an exception is raised? Well, I can handle it using the except clause. In this case, I try my routine, pass an invalid value,
06:43
get an exception. And if I print the exception, I get the error message on the screen. In this case, I would get the result, height is minus 3 but must be greater than 0. When I want to clean up after errors, Python has several mechanisms.
07:00
Here's a simple one or the first one. In case of a file, I try to open the file. If it works out, I try to process the data I read from the file. And finally, I just clean up by closing the file. The interesting thing about that, finally closes the file independent if there's an error or not.
07:20
It will always close the file. I could also use the with statement for that. It has a little bit different syntax, less code, and gives the same result. In order for the with statement to work, you need a context manager. So the class you use, in this case, a file object, needs to provide a context manager.
07:43
I'm going to rush through this a bit. I can simply add a context manager on the fly using the closing routine, which is very useful in Python 2, less in Python 3 because most of the standard objects already have a context manager. But in this case, I can add one
08:00
by calling the result in a closing. When you want to write your own context manager, and then you have to add basically two standard routines to a class. Here's a very simple example. This is a task to copy a file. The initial part just allocates the source file
08:22
and the target file to open it. There is a run part, which runs the task, and it simply copies the bytes from one file to the other. And there is a clean up routine called close, which closes the two files. I said naive variant because it doesn't do any error handling yet.
08:41
I could use this naive variant the way it is with a try and finally to open a copy task, run it, and execute it, and clean up the resources afterwards. If I want to do that with a context manager and a with clause, I just have to add two routines, enter and exit.
09:01
And it will always look like that. The context manager can do a lot of things, but if you just want to use it in a with clause, there's nothing more to it. As soon as you have a close and an initializer that allocates all the resources and the close routine that gives all of them back, that's the context manager, these four lines of code.
09:23
And once you added these, you can use it with the with clause. What's happening here? The with clause basically calls the init function at the part where you create the object. Once you assign it to a variable, it calls the enter function and assigns the result of enter to the variable.
09:45
And once the whole with clause ends, it calls the exit function. That's basically what context managers do. And I think it's a very simple way to not bother much about giving back resources. Here's an example of an improved context manager
10:03
because the initial variant basically only allocated the resources. And you can run in a case when you allocate multiple resources that the initializer already breaks after allocating the source file, but it cannot open the target file and you want to make sure to give back the target file.
10:22
So you basically remember all the resources initialized and with none and make the close routine a bit smarter. Only close those files that are not none and the init also checks for errors and if there is an error, it calls the close beforehand. So pretty simple principle. And then there's another statement to detect errors.
10:42
We already talked about race. There also is assert. How many people know the assert statement or have used it already? Okay. How many people think they know when to use assert and when to use race? Yes, already.
11:00
So I would say it was about a third who know about them and about 10% who think they know when to use it properly. Okay, what is the assert statement? Well, I could also detect an error using assert as again the previous example with the race. I can do the same with assert by just specifying a condition.
11:23
In this case, it's not the error condition, but the condition for the correct state. Hate must be greater than zero and provide an error message which is optional in this case. There is a couple of differences with assert. Internally, it just raises an assertion error.
11:40
So to some extent, it is comparable with race. However, you can deactivate it. If you run Python from the command line with the minus O switch, not the digit zero, it deactivates the checking of assertions which might increase performance a little and might remove consistency checks.
12:02
Functions called by assert therefore must not have any side effects because otherwise the program starts to behaving differently whether minus O specified or not. And the question now is, when do we use race and when do we use assert? This is something I'm going to talk about a little bit later.
12:21
So in summary, the gist of Python's exception handling is that you can detect errors with race or assert. You can deal with errors using try and accept and you can clean up using finally closing or context managers. These are the tools Python gives you when you install it.
12:42
Everything of this is already there. So the interesting part is now how do I use all this in a solution-oriented way? And the principles of solution-oriented error handling are that you focus on the solution and not on what's wrong. You have clear responsibilities
13:00
between developers and the user and operator. You have helpful and specific error messages and error conditions and error messages can be derived from the code. So it is a developer-centric approach. When I talk about responsibilities, let's take a look at the graphics that we had before.
13:23
The responsibility of the user and the operators is pretty clear. They have to provide sufficient, complete and valid input for the program to produce the result. The operators have to provide an environment where the program has everything it needs concerning access rights, memory and so on.
13:41
And the developer has the responsibility to write the program. So that's something important to remember. All we can do is write the program. We cannot add memory at the user's side. We cannot add or change input so that it works. The user has to do that.
14:03
However, we also have another responsibility. If the program cannot produce the result, we have to provide helpful information to the user or we have to make the program to provide helpful information to the user so that they can fix any errors on site.
14:24
How can we do that using Assert? Well, Assert is a tool to detect errors by checking the internal program state. Ideally, it detects errors before the program is delivered. So it's a tool for the developer.
14:42
And if an assertion fails, the developer has to fix the error by changing the code. Maybe he has to cover new requirements and whatnot, but at the end of the day, he will have to change the code for the assertion to go away. So the target audience for the assertion clearly is the developer and assertions are there to detect bugs in the program.
15:02
Assertions are a very useful tool to establish clear responsibilities between caller and calling routines. You can particularly use it to validate parameters and point out invalid parameters. So that's something in Python where I use it a lot.
15:23
This is called preconditions. And assertions provide executable documentation. So it's better to write assertions which actually check if a parameter is correct than to write a documentation nobody reads and that might get out of date. Assertions are executed every time the program runs.
15:41
So once the assertion gets out of date, you have to fix the assertion. On the other hand, arrays, you can use to detect errors in the data and environment in things the user and the operators can solve. So they can provide valid data, complete input, or they can provide a sufficient environment with enough memory, disk space,
16:02
and connections, network connections. Arrays is something to point out conditions the developer cannot deal with at the time he writes the program. He has no influence in these conditions. The target audience clearly are the users and the operations. So a couple of words on wording error messages.
16:23
Well, you have a lot of usability guidelines and books about it written by usability people, but very often they are too vague for developers to actually turn them into code. So error messages should be polite, precise, constructive. Well, how do I actually do that? And in practice, you see that many error messages
16:40
talk a lot about the things that are wrong and not about what should I do, what's actually precisely wrong, what can I do, what are my possibilities? So the solution-oriented approach to error messages is that they describe the actual state and value and the one that would have been expected. They describe the actions necessary to solve the error
17:03
and they describe the actions that led to an error to provide context where the error comes from. So how does it look in terms of code? Oh, there was one slide ahead. How does it look in terms of code? Generally, code to detect errors looks like that.
17:23
If an actual value is not the expected value, then I raise some error with the message actual must be expected. So, and I already have these in my code. Here's an example. We already know it. If hate is less or smaller than zero,
17:41
I raise a value arrow which says hate must be greater than zero. How do I describe the solution? Well, I already did. I already told them hate must be greater than zero. So from this error message, the user just has to do whatever is necessary
18:00
to establish the expected condition. For that, of course, he has to understand the program and how to use it. Couple of more examples for such error messages. Date of birth must match a certain date format. The option color in the section layout of the config file must be one of red, green, blue.
18:22
So how do I describe the action and the value that led to the error? When I raise an error, I just specify the value I used in my error condition. So in my case, hate had the value minus zero. And I just add it to the error message.
18:41
The error message says hate is zero, but must be greater than, hate is minus three, but must be greater than zero. When I get an error already from a calling routine and I catch it with the except statement, I don't know what the initial condition was. So I just have to rely on the initial message.
19:00
However, I can add the context in which the error occurred. So I just describe the action that could not be performed typically I cannot process, I cannot connect to a host, I cannot write to a file, I cannot use the value of a form in a certain field. So I describe the item.
19:22
And in this message, I have to use the terms the user knows. So not my variable names, which ideally are the same, but something the user knows. And then all the information in the error message is something the user should be able to deal with provided he has enough knowledge about software
19:40
and how to use it. Let's take a look at an example. We already know this routine. It is process something and gets a hate variable or a hate parameter and raises an exception if it is not in the valid range. Here's a routine that would process hate values
20:02
it gets from file. So basically it opens a file, reads a line, converts it to an integer, and checks for errors. If everything goes wrong, if everything goes right, there is no exception. If there is an exception,
20:21
it writes an error message which says cannot process data in file. And the file name, line, and the line number, and the actual error message it got in the value error. And in summary, the output of this in case of error would be cannot process data file, some text, line 17,
20:42
hate is minus three but must be greater than zero. And basically you get all this for free from your code you already wrote. So in summary, a pattern for error messages is cannot perform an action at a certain location, something is actual but must be expected.
21:01
And you should have all of this available in your code. A couple of words on exception hierarchy to make it easier for you. Exceptions are classes in Python that are organized in a hierarchy which allows you to collect similar exceptions in groups and deal with them in the same way.
21:23
So we can use this to assign responsibilities. It's already pretty clear that developers should fix assertion errors. In my experience, it's pretty clear that users and operators should fix OS errors. However, there is a quite large amount of exceptions where you can't really say who's responsible to fix it.
21:43
So it's your task to make this more specific. In my experience, I usually just define a data error because that's the errors about user input users can fix. And when I detect something invalid, I just raise a data error.
22:00
Exceptions raised by other routines, value error, index error, lookup error, very often indicate at the data error. So I just catch them with accept and re-raise them as data error again. Here's an example how to define a data error. Pretty easy in Python.
22:20
How do I convert a value error to a data error? I just catch the value error and raise the data error where I leave the original message intact. In Python 3, you can also preserve the stack trace by using exception chaining. Here's a little example for that.
22:41
So a solution-oriented exception hierarchy basically comes down to users fix data error and OS error, and the developer fixes everything else, in particular, assertion error. Couple of recommendations for accept and raise. When do I use accept?
23:03
You have to use it at the utmost layer of your main routine and print an error message or do something useful with every exception. In graphical applications, you should use it for every enclosed user operation or action pattern, as developers call it. If enclosed operation fails,
23:22
you can say this operation failed and you have to establish this or that condition. You should also use accept to convert other exceptions to data error, as I've just shown, to make it clear who's responsible. And you can use accept to convert errors
23:41
into valid states, which is a bit of a risky principle, but where it works reasonably well is, for example, to provide default values for things that are simply not there. So generally, you hardly ever use accept, and by end, you use it in a tightly focused way, which means little work for the developer
24:01
and which also means that the error handling in your code becomes very easy. Because most of the time, you just clean up. If there's an error, you don't care because you can't fix it. The user has to fix it, the operator has to fix it. So you just clean up and it traverses upwards the stack.
24:20
Eventually, one of the calling routines will decide how to deal with it, but it's not your problem at that moment. The nice thing is that you don't have to care about producing the result because the exception mechanism already stops the productive part of your code. And the benefit of all this is you have a clean code focusing on producing the result,
24:42
and it doesn't intermingle with try, accept, and whatnot. When do I detect an error? Well, it's pretty easy if you use natural naming in your code. It means the routines in your code have the same name as the things they're supposed to perform,
25:00
and functions have the name of the things they're supposed to return because then an error condition is when it cannot do the thing it's supposed to perform, as the name suggests, or it cannot return the result it's supposed to return. That's an error condition. And in that case, you just raise or assert.
25:23
Okay, here's a small template for a command line application, how to apply that. The interesting part is, the most interesting part is here. You have a production code that should produce a result. If it cannot do, it handles the data error and OS error.
25:41
Five and two. And if there's anything else, it just logs the exception, including the stack trace. And that's all there is. And if it's a simple command line application, there is not a single accept statement in it. There's maybe a couple of race statements where it detects certain error conditions, but other than that, you don't have to bother about error handling.
26:01
And it gives exit code zero or one, depending on the general state. Okay, so in summary, solution-oriented error handling is a set of guidelines to efficiently use Python's exception handling. The core consideration is who can fix the error. Users can fix errors during run time
26:22
if they are data errors or OS errors. Developers can fix errors during the implementation if they are exceptions or assertions or other exceptions. And you always clean up in case of error. And you always clean up even if the result is produced with finally
26:40
the with statement and context managers. So error handling code basically consists of detecting a couple of conditions that indicate errors, raise and assert them. Most of the time just delegate the exceptions and at a few specific locations catch them with accept.
27:00
And the pattern for helpful error messages cannot perform action at location. Something is actual but must be expected, which automatically describes the solution to the error. Okay, questions.
27:23
Thank you Thomas, any questions? We've got one minute. There are two microphones. Okay, go ahead please. Yeah, do you know if there is a way to emulate the from error from Python 3 and Python 2? Sorry, I can't understand you. Is there a way to emulate the from error syntax
27:42
from Python 3 and Python 2? Only by hacking around. There's no clean way. You can use the original stack trace in your old exception. But I think you have to go down into dirty meta programming to actually do it. I've never done it myself. Okay, thanks.
28:03
I think we've run out of time for questions. So if you could give one final round of applause to Thomas. Thank you very much. Thank you.