Is a program error that occurs when the programmer has not followed the rules of the programming language?
Back in the old days, long before our understanding of coding became what it is today, programming errors could be truly disastrous. Luckily for us all, modern coding approaches and debugging systems make it a lot easier to fix these mistakes. Show
The 7 most commonly encountered programming errors are: 1. Runtime errorsThese bugs occur when the code “won’t play nice” with another computer, even if it worked perfectly fine on the developer’s own computer. These errors are especially frustrating because they directly impact the end user and make the application appear unreliable or even completely broken. 2. Logic errorsThese errors can be extremely frustrating to deal with because nothing is inherently wrong with the code: the developer just didn’t program the computer to do the correct thing. In fact, a logic error caused by miscalculations between American and English units caused NASA to lose a spacecraft in 1999. 3. Compilation errorsCompilation is the process of converting a high-level coding language into a lower-level language that can be better understood by the computer. Compilation errors occur when the compiler isn’t able to properly transform the high-level code into the lower-level one. This prevents the software from being launched or tested. 4. Syntax errorsComputer languages have their own specialized grammar rules. When these rules aren’t followed (for example, the developer omits the parentheses while writing code), a syntax error prevents the application from running. 5. Interface errorsThese bugs typically happen when the inputs the software receives do not conform to the accepted standards. When handled incorrectly, these errors can look like errors on your side even when they’re on the caller’s side, and vice versa. 6. Resource errorsSometimes, a program can force the computer it’s running on to attempt to allocate more resources (processor power, random access memory, disk space, etc.) than it has. This results in the program becoming bugged or even causes the entire system to crash. 7. Arithmetic errorsThese errors are just like logic errors, but with mathematics. For example, a division equation may require the computer to divide by zero. Since this is mathematically impossible, it results in an error that prevents the software from working correctly. Where can I find the most reliable remote coding bootcamp in San Diego?Understanding the common programming errors and learning how to deal with them is an essential skill that every web developer should have. At Learn Academy, we can teach you how to do just that, and much more, in one of our intensive coding bootcamps. But what if you don’t want to leave your home due to the coronavirus pandemic? No worries! Our online coding bootcamps are available to all students regardless of whether they live in the Linda Vista neighborhood of San Diego, or in another state entirely. Contact us today. Errors¶Errors or mistakes in a program are often referred to as bugs. They are almost always the fault of the programmer. The process of finding and eliminating errors is called debugging. Errors can be classified into three major groups:
Syntax errors¶Python will find these kinds of errors when it tries to parse your program, and exit with an error message without running anything. Syntax errors are mistakes in the use of the Python language, and are analogous to spelling or grammar mistakes in a language like English: for example, the sentence Would you some tea? does not make sense – it is missing a verb. Common Python syntax errors include:
Note it is illegal for any block (like an Python will do its best to tell you where the error is located, but sometimes its messages can be misleading: for example, if you forget to escape a quotation mark inside a string you may get a syntax error referring to a place later in your code, even though that is not the real source of the problem. If you can’t see anything wrong on the line specified in the error message, try backtracking through the previous few lines. As you program more, you will get better at identifying and fixing errors. Here are some examples of syntax errors in Python: myfunction(x, y): return x + y else: print("Hello!") if mark >= 50 print("You passed!") if arriving: print("Hi!") esle: print("Bye!") if flag: print("Flag is set!") Runtime errors¶If a program is syntactically correct – that is, free of syntax errors – it will be run by the Python interpreter. However, the program may exit unexpectedly during execution if it encounters a runtime error – a problem which was not detected when the program was parsed, but is only revealed when a particular line is executed. When a program comes to a halt because of a runtime error, we say that it has crashed. Consider the English instruction flap your arms and fly to Australia. While the instruction is structurally correct and you can understand its meaning perfectly, it is impossible for you to follow it. Some examples of Python runtime errors:
Runtime errors often creep in if you don’t consider all possible values that a variable could contain, especially when you are processing user input. You should always try to add checks to your code to make sure that it can deal with bad input and edge cases gracefully. We will look at this in more detail in the chapter about exception handling. Logical errors¶Logical errors are the most difficult to fix. They occur when the program runs without crashing, but produces an incorrect result. The error is caused by a mistake in the program’s logic. You won’t get an error message, because no syntax or runtime error has occurred. You will have to find the problem on your own by reviewing all the relevant parts of your code – although some tools can flag suspicious code which looks like it could cause unexpected behaviour. Sometimes there can be absolutely nothing wrong with your Python implementation of an algorithm – the algorithm itself can be incorrect. However, more frequently these kinds of errors are caused by programmer carelessness. Here are some examples of mistakes which lead to logical errors:
If you misspell an identifier name, you may get a runtime error or a logical error, depending on whether the misspelled name is defined. A common source of variable name mix-ups and incorrect indentation is frequent copying and pasting of large blocks of code. If you have many duplicate lines with minor differences, it’s very easy to miss a necessary change when you are editing your pasted lines. You should always try to factor out excessive duplication using functions and loops – we will look at this in more detail later. Exercise 1¶
Handling exceptions¶Until now, the programs that we have written have generally ignored the fact that things can go wrong. We have have tried to prevent runtime errors by checking data which may be incorrect before we used it, but we haven’t yet seen how we can handle errors when they do occur – our programs so far have just crashed suddenly whenever they have encountered one. There are some situations in which runtime errors are likely to occur. Whenever we try to read a file or get input from a user, there is a chance that something unexpected will happen – the file may have been moved or deleted, and the user may enter data which is not in the right format. Good programmers should add safeguards to their programs so that common situations like this can be handled gracefully – a program which crashes whenever it encounters an easily foreseeable problem is not very pleasant to use. Most users expect programs to be robust enough to recover from these kinds of setbacks. If we know that a particular section of our program is likely to cause an error, we can tell Python what to do if it does happen. Instead of letting the error crash our program we can intercept it, do something about it, and allow the program to continue. All the runtime (and syntax) errors that we have encountered are called exceptions in Python – Python uses them to indicate that something exceptional has occurred, and that your program cannot continue unless it is handled. All exceptions are subclasses of the The try and except statements¶To handle possible exceptions, we use a try-except block: try: age = int(input("Please enter your age: ")) print("I see that you are %d years old." % age) except ValueError: print("Hey, that wasn't a number!") Python will try to process all the statements inside the try block. If a In this example, we know that the error is likely to occur when we try to convert the user’s input to an integer. If the input string is not a number, this line will trigger a We could have specified a more general type of error – or even left the type out entirely, which would have caused the
It is possible for one try: dividend = int(input("Please enter the dividend: ")) divisor = int(input("Please enter the divisor: ")) print("%d / %d = %f" % (dividend, divisor, dividend/divisor)) except(ValueError, ZeroDivisionError): print("Oops, something went wrong!") A try-except block can also have multiple try: dividend = int(input("Please enter the dividend: ")) divisor = int(input("Please enter the divisor: ")) print("%d / %d = %f" % (dividend, divisor, dividend/divisor)) except ValueError: print("The divisor and dividend have to be numbers!") except ZeroDivisionError: print("The dividend may not be zero!") Note that in the example above if a
try: dividend = int(input("Please enter the dividend: ")) except ValueError: print("The dividend has to be a number!") try: divisor = int(input("Please enter the divisor: ")) except ValueError: print("The divisor has to be a number!") try: print("%d / %d = %f" % (dividend, divisor, dividend/divisor)) except ZeroDivisionError: print("The dividend may not be zero!") In general, it is a better idea to use exception handlers to protect small blocks of code against specific errors than to wrap large blocks of code and write vague, generic error recovery code. It may sometimes seem inefficient and verbose to write many small try-except statements instead of a single catch-all statement, but we can mitigate this to some extent by making effective use of loops and functions to reduce the amount of code duplication. How an exception is handled¶When an exception occurs, the normal flow of execution is interrupted. Python checks to see if the line of code which caused the exception is inside a try block. If it is, it checks to see if any of the except blocks associated with the try block can handle that type of exception. If an appropriate handler is found, the exception is handled, and the program continues from the next statement after the end of that try-except. If there is no such handler, or if the line of code was not in a try block, Python will go up one level of scope: if the line of code which caused the exception was inside a function, that function will exit immediately, and the line which called the function will be treated as if it had thrown the exception. Python will check if that line is inside a try block, and so on. When a function is called, it is placed on Python’s stack, which we will discuss in the chapter about functions. Python traverses this stack when it tries to handle an exception. If an exception is thrown by a line which is in the main body of your program, not inside a function, the program will terminate. When the exception message is printed, you should also see a traceback – a list which shows the path the exception has taken, all the way back to the original line which caused the error. Error checks vs exception handling¶Exception handling gives us an alternative way to deal with error-prone situations in our code. Instead of performing more checks before we do something to make sure that an error will not occur, we just try to do it – and if an error does occur we handle it. This can allow us to write simpler and more readable code. Let’s look at a more complicated input example – one in which we want to keep asking the user for input until the input is correct. We will try to write this example using the two different approaches: # with checks n = None while n is None: s = input("Please enter an integer: ") if s.lstrip('-').isdigit(): n = int(s) else: print("%s is not an integer." % s) # with exception handling n = None while n is None: try: s = input("Please enter an integer: ") n = int(s) except ValueError: print("%s is not an integer." % s) In the first code snippet, we have to write quite a convoluted
check to test whether the user’s input is an integer – first we strip off a minus sign if it exists, and then we check if the rest of the string consists only of digits. But there’s a very simple criterion which is also what we really want to know: will this string cause a Here are a few other advantages of exception handling:
The else and finally statements¶There are two other clauses that we can add to a try-except block: try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) We want to print a message about the user’s age only if the integer conversion succeeds. In the first exception handler example, we put this print statement directly after the conversion inside the When we edit this program in the future, we may introduce additional statements that should also be executed if the age input is successfully converted. Some of these statements may also potentially raise a The try: age = int(input("Please enter your age: ")) except ValueError: print("Hey, that wasn't a number!") else: print("I see that you are %d years old." % age) finally: print("It was really nice talking to you. Goodbye!") Exercise 2¶
The with statement¶Using the exception object¶Python’s exception objects contain more information than just the error type. They also come with some kind of message – we have already seen some of these messages displayed when our programs have crashed. Often these messages aren’t very user-friendly – if we want to report an error to the user we usually need to write a more descriptive message which explains how the error is related to what the user did. For example, if the error was caused by incorrect input, it is helpful to tell the user which of the input values was incorrect. Sometimes the exception message contains useful information which we want to display to the user. In order to access the message, we need to be able to access the exception object. We can assign the object to a variable that we can use inside the try: age = int(input("Please enter your age: ")) except ValueError as err: print(err)
try: age = int(input("Please enter your age: ")) except ValueError as err: print("You entered incorrect age input: %s" % err) Note that inserting a variable into a formatted string using Raising exceptions¶We can raise exceptions ourselves using the try: age = int(input("Please enter your age: ")) if age < 0: raise ValueError("%d is not a valid age. Age must be positive or zero.") except ValueError as err: print("You entered incorrect age input: %s" % err) else: print("I see that you are %d years old." % age) We can raise our own We picked
We can also write our own custom exception classes which are based on existing exception classes – we will see some examples of this in a later chapter. Something we may want to do is raise an exception that we have just intercepted – perhaps because we want to handle it partially in the current function, but also want to respond to it in the code which called the function: try: age = int(input("Please enter your age: ")) except ValueError as err: print("You entered incorrect age input: %s" % err) raise err Exercise 3¶
Debugging programs¶Syntax errors are usually quite straightforward to debug: the error message shows us the line in the file where the error is, and it should be easy to find it and fix it. Runtime errors can be a little more difficult to debug: the error message and the traceback can tell us exactly where the error occurred, but that doesn’t necessarily tell us what the problem is. Sometimes they are caused by something obvious, like an incorrect identifier name, but sometimes they are triggered by a particular state of the program – it’s not always clear which of many variables has an unexpected value. Logical errors are the most difficult to fix because they don’t cause any errors that can be traced to a particular line in the code. All that we know is that the code is not behaving as it should be – sometimes tracking down the area of the code which is causing the incorrect behaviour can take a long time. It is important to test your code to make sure that it behaves the way that you expect. A quick and simple way of testing that a function is doing the right thing, for example, is to insert a print statement after every line which outputs the intermediate results which were calculated on that line. Most programmers intuitively do this as they are writing a function, or perhaps if they need to figure out why it isn’t doing the right thing: def hypotenuse(x, y): print("x is %f and y is %f" % (x, y)) x_2 = x**2 print(x_2) y_2 = y**2 print(y_2) z_2 = x_2 + y_2 print(z_2) z = math.sqrt(z_2) print(z) return z This is a quick and easy thing to do, and even experienced programmers are guilty of doing it every now and then, but this approach has several disadvantages:
How can we do this better? If we want to inspect the values of variables at various steps of a program’s execution, we can use a tool like Most importantly, to check that our code is working correctly now and will keep working correctly, we should write a permanent suite of tests which we can run on our code regularly. We will discuss testing in more detail in a later chapter. Logging¶Sometimes it is valuable for a program to output messages to a console or a file as it runs. These messages can be used as a record of the program’s execution, and help us to find errors. Sometimes a bug occurs intermittently, and we don’t know what triggers it – if we only add debugging output to our program when we want to begin an active search for the bug, we may be unable to reproduce it. If our program logs messages to a file all the time, however, we may find that some helpful information has been recorded when we check the log after the bug has occurred. Some kinds of messages are more important than others – errors are noteworthy events which should almost always be logged. Messages which record that an operation has been completed successfully may sometimes be useful, but are not as important as errors. Detailed messages which debug every step of a calculation can be interesting if we are trying to debug the calculation, but if they were printed all the time they would fill the console with noise (or make our log file really, really big). We can use Python’s There is a consistent set of logging level names which most languages use. In order, from the highest value (most severe) to the lowest value (least severe), they are:
These names are used for integer constants defined in the import logging # log messages to a file, ignoring anything less severe than ERROR logging.basicConfig(filename='myprogram.log', level=logging.ERROR) # these messages should appear in our file logging.error("The washing machine is leaking!") logging.critical("The house is on fire!") # but these ones won't logging.warning("We're almost out of milk.") logging.info("It's sunny today.") logging.debug("I had eggs for breakfast.") There’s also a special try: age = int(input("How old are you? ")) except ValueError as err: logging.exception(err) If we have a large project, we may want to set up a more complicated system for logging – perhaps we want to format certain messages differently, log different messages to different files, or log to multiple locations at the same time. The logging module also provides us with logger and handler objects for this purpose. We can use multiple loggers to create our messages, customising each one independently. Different handlers are associated with different logging locations. We can connect up our loggers and handlers in any way we like – one logger can use many handlers, and multiple loggers can use the same handler. Exercise 4¶
Answers to exercises¶Answer to exercise 1¶
Answer to exercise 2¶
Answer to exercise 3¶
Answer to exercise 4¶
What is an error in a program called?A software bug is an error, flaw or fault in the design, development, or operation of computer software that causes it to produce an incorrect or unexpected result, or to behave in unintended ways.
What are the 3 types of error in programming?3 Types of Programming Errors and How to Avoid Them. Runtime or Execution Errors. These are errors that occur when a program is executing (i.e. at runtime). ... . Logic Errors. Logic errors are caused due to flawed reasoning. ... . Syntax or Compile-Time Errors. These are errors caused due to violations of Java's language rules.. What is a programmer error?Programming error means an error which occurs during the development or encoding of a computer program, software, or application, which would, when in operation, result in a malfunction or incorrect operation of a computer network.
Which error violates the rules of programming language?Syntax errors: Errors that occur when you violate the rules of writing C/C++ syntax are known as syntax errors. This compiler error indicates something that must be fixed before the code can be compiled. All these errors are detected by compiler and thus are known as compile-time errors.
|