What is logical error

What is logical error 12.5.3.5 describe a syntax error in a programming 12.5.3.1 describe run-time errors in a programming 12.5.3.6 describe a logic error in a programming Types of programming errors Errors are the mistakes or faults in the program that causes our program to behave unexpectedly and it is no doubt that well-versed […]

Содержание

  1. What is logical error
  2. Logic Error
  3. What Does Logic Error Mean?
  4. Techopedia Explains Logic Error
  5. Difference between “Syntax Errors“ and “Logical Errors“ in programming
  6. Two words that for someone could be confusing. Let’s explain them!
  7. The problem considered and a solution
  8. Syntax errors
  9. What is a syntax error?
  10. Logical errors
  11. What are logical errors?
  12. Conclusion
  13. Types of Programming Errors and How to Avoid Them
  14. Example
  15. What is Programming?
  16. What if errors occur in Programming?
  17. ERROR
  18. BUG
  19. DEFECT OR FAULT
  20. FAILURE
  21. How errors can be found?
  22. Types of error:
  23. Syntax Error
  24. How to avoid syntax error:
  25. Logical Error
  26. How to avoid Logical error:
  27. Semantic Error
  28. How to avoid Semantic error:
  29. Arithmetic Error
  30. How to avoid the Arithmetic error:
  31. Resource Error
  32. How to avoid Resource error:
  33. Interface Error
  34. How to avoid Interface error:
  35. Runtime or Execution Error
  36. How to avoid the error:
  37. Compilation Error
  38. How to avoid the error:

What is logical error

12.5.3.5 describe a syntax error in a programming
12.5.3.1 describe run-time errors in a programming
12.5.3.6 describe a logic error in a programming

Types of programming errors

Errors are the mistakes or faults in the program that causes our program to behave unexpectedly and it is no doubt that well-versed and experienced programmers also make mistakes. Programming errors are generally known as Bugs and the process to remove bugs from the program is called Debug/Debugging.

There are basically three types of error:

  1. Syntax error or Compilation error
  2. Runtime error or Execution error
  3. Logical error

Syntax error or Compilation error
Compilation errors are the most common error occurred due to typing mistakes or if you don’t follow the proper syntax of the specific programming language. These errors are thrown by the compilers and will prevent your program from running. These errors are most common to beginners. It is also called a Compile time error or Syntax error. These errors are easy to debug.

  • misspelling a statement, eg writing iput instead of input or typing Int instead of int
  • missing brackets, eg opening a bracket, but not closing it
  • missing semicolon
  • errors in the sequence of expressions

Runtime error (Execution error)
Run Time errors are generated when the program is running and lead to abnormal behavior or termination of the program. The general cause of Run time errors is because your program is trying to perform an operation that is impossible to carry out.

  • Dividing any number by zero,
  • Accessing any file that doesn’t exist,
  • Negative value under a square root,
  • Calling invalid functions,
  • Not handling certain input correctly (ex. not appropriate data type),
  • Out of bounds of array indices.

Logical error
The logical error will cause your program to perform undesired operations that you didn’t intend your program to perform. These errors occur generally due to improper logic used in the program. These types of errors are difficult to debug.

  • errors in the performed computation, eg. using multiplication (a * b) instead of adding (a + b)
  • errors in the performed condition, eg. using «
  • unintentionally creating a situation where an infinite loop may occur
  • incorrectly using brackets in calculations
  • unintentionally using the same variable name at different points in the program for different purposes.

Table for comparison of types of errors

Type of error Compilation Execution
Syntax error
Run-time error
Logic error

Questions:

1. Explain what is a programming error.

2. Describe the term «syntax error».

3. Explain what difference between run-time error and logic error.

Источник

Logic Error

Table of Contents

What Does Logic Error Mean?

A logic error is an error in a program’s source code that gives way to unanticipated and erroneous behavior. A logic error is classified as a type of runtime error that can result in a program producing an incorrect output. It can also cause the program to crash when running.

Logic errors are not always easy to recognize immediately. This is due to the fact that such errors, unlike that of syntax errors, are valid when considered in the language, but do not produce the intended behavior. These can occur in both interpreted and compiled languages.

A logic error is also known as a logical error .

Techopedia Explains Logic Error

Logic errors cause a program to work incorrectly. For example, in PHP, when «if ($i=1) <…>» is incorrectly entered instead of «if ($i==1) <….>,» the former means «becomes» while the latter means «is equal to.» The incorrect if statement would always return TRUE as assigning 1 to the variable $i. In the correct version, though, the statement only returns TRUE when the value of variable $i is equal to 1. The syntax in the incorrect case is perfectly correct as per the language. So, the code would compile successfully without producing any syntax errors. However, during runtime of the code, the resultant output may be wrong, thus showing that a certain logic error has occurred. Logic errors tend to be hidden in the source code and can typically be harder to determine and debug, unlike syntax errors that are recognized at compile time.

Источник

Difference between “Syntax Errors“ and “Logical Errors“ in programming

Two words that for someone could be confusing. Let’s explain them!

The problem considered and a solution

Let’s suppose we have an array of int types and we want to print them in sequence to the screen in the following way: “output: 1 2 3 4 5“.

Now let’s understand what I could have made wrong.

Syntax errors

Look at the following code:

The two files posted above are equal? Look at them.

They are not equal. In the second one I wrote “ i lengt“? I don’t know, you probably don’t know, the compiler surely doesn’t know. Here is the point! If you try to compile the second file the process will not succeed. The compiler will protest with a « error: cannot find symbol» message. This is a syntax error!

What is a syntax error?

An syntax error occurs when during compilation the compiler finds something in your code it doesn’t know what it means, or it not sure how to translate what you wrote. The compiler will always advise you about syntax errors, even though sometimes it could be wrong about the line (or lines) where the error occurred.

Look at the following example:

Where is the error?

I wrote “System.out.printlnnumbers);“. What is “printlnnumbers);“?? It is quite easy for us to understand that I forgot to write the “(“ bracket. The compiler didn’t get it and it tells me:

  • I didn’t write a statement -> quite right, what I wrote it is not a valid statement.
  • “;“ expected -> False, I wrote the semicolon at the end!

So pay attention. The compiler advises you but sometimes it could miss the real problem.

Logical errors

Look at the following code:

What changed? Try to figure it out.

In the for loop this time I started from 1, I wrote “int i = 1;“. Is it an error? It depends. On what? On what we wanted to do. I mean, it is not a syntax error (try to convince you), so the compiler wouldn’t protest. The program would be finally executable but the output wouldn’t be the one we expected. Why? We initialized the variable “i“ from value “1“ so we will print the values of the array from the second element (arrayEx[1] is the second element!). This is is a logical error!

What are logical errors?

They are errors which occurs when the program executes but doesn’t do what we expected. They are the most difficult to identify because the compiler doesn’t do nothing for you (the program has already been compiled).

Some logical errors are so serious that exceptions are thrown (you can throw exceptions in your program too).

In this code in the for loop, the condition changed. I wrote “i I added the “=“ operator! So? It means also the value of “i“ equal to “arrayEx.length“ will be used as index for the array, but that index doesn’t exist in that array. An “ ArrayIndexOutOfBoundsException“ will be thrown.

Conclusion

I hope I helped you to understand better the difference between “ syntax errors“ and “ logical errors“.

If you have an argument you want me to discuss about tell me in the comments.

Do you know the difference between “ argument“ and “ parameter“ in programming? I wrote an article about it.

Источник

Types of Programming Errors and How to Avoid Them

The programming errors, don’t you think it’s quite an intersecting thing to understand. What could be the meaning of the word ERROR in layman language? Error is something quite close to word mistake, isn’t it? You people might hear about the word ERROR so many times whether you are in the technology field or not. Actually, the error is a problem or you can say a wrong action which results in a problem. It could be an incorrect thing done related to programming, in development, or in the system.

So on average, we can think that if we are trying to get a predictable result from some code or system or program or any other way. But due to some input or action, we are not getting the desired result. So we can say that there is some problem or error in that action.

Example

Let’s illustrate it with a very simple example. You will understand that it’s quite a simple way of calculation. I know that the addition of 3+2 is going to give me result 5 in the answer but what if I am not able to get that result. Say I am trying to get that result through programming or through any system or software. That sort of thing that does not lead me to the desired result comes under the term ERROR.

It’s just a brief scenario that I tried to present to you but that area is quite vast and our main focus is only on the discussion of ERROR. I will also give you an idea that how an error is different from any bug, failure, fault, or defect. So what actually Error is basically kind of result deviation between predictable and actual result.

What is Programming?

OK, let’s deep dive into the world of programming errors. So what usually happens, I am trying to explain in the computer programming field, whenever a beginner tries to start programming. I am assuming you are already aware of term programming. If not, don’t worry that is not a big issue. Let me make you understand it first. Programming is a way to create some steps having some rules to follow by the computer system so that it can perform a particular task.

Programming is not only fixed to just one language. As a computer field person knows very well that there are several programming languages. We can do programmings like C, C++, Java, Python, Javascript, and many more. So programming is a task that is quite creative.

We cannot say that to do any task there would be only one right way. There could be other ways to perform the same task and they can also fall in a better category as compared to the other ones. You know with more practice and knowledge people are able to do better programming. You can say with experience, a person will be able to know better ways of writing any program. Along with that logical skills matter a lot. That is all about programming. You need not worry about it much. You would be able to find many definitions related to programming that can help you to understand its meaning better.

Coming back to our main focus ERROR. So what you think could be a reason for getting error in programming. Say you are new to the world of programming; you just started to make a program in C++ language. don’t you think you may lead to a few problems?

What if errors occur in Programming?

I am not saying that your programming will always lead to error. But what I am trying to say is what will happen when you encounter a problem. Just don’t worry about the statement. If a problem occurs, then there’s always a solution. You only have to find out a way to understand that problem completely. Then just resolve it or fix it in terms of programming.

But before all, you should be aware of some common types of errors that you could encounter while programming. If you have an idea about a problem then it should not remain as a hurdle anymore on your track rather that you can fight with that problem. It does not matter whether you are a good programmer or not, smart enough for programming or not, errors are your companion.

The only way to get rid of these errors is more and more practice. So that you can be able to do your programming task in a better way. Before all let me give you an idea about things like bug, failure, Fault, or defect. Just don’t think that errors only occur in programming. They could occur in the software or in any other areas also.

ERROR

Whenever a programmer does make any program say in any language either C, C++, or any other. The programmer tries to get the desired output from it. But somehow due to some mistake programmer is not able to get the desired result. Then that mistake in the program commonly considered as error. You can also say that it’s a wrong human action that produces the wrong result. There could be many reasons for it as follows:

  • A person is having any confusion in the output of the program while making it.
  • Adaption of a wrong idea or wrong calculation can lead to error.
  • Taking any wrong meaning of any value in the program during coding.
  • These errors usually occur due to wrong lops or syntax.
  • For example error in data handling or in the configuration.

BUG

It’s a sort of error in programming that usually occurs in any application before getting developed or created. The bug does not lead to any genuine problem. it’s something that we never expected due to which program performs irrationally. Also, the response provided is incorrect leading to the crash of the system.

  • For example, when you try to divide a number by zero in the program it leads to a bug.
  • Other reasons for bug include Infinite loops and the use of uninitialized variables.

DEFECT OR FAULT

This term usually comes to light when we consider software. The main reason for a defect is the deviation of the performance of the software. When software is produced that is not according to user requirement. I mean to say it’s not giving the same output as expected by the customer. So we can say it’s a kind of defect or Fault. But it’s different from a bug because a bug is detected earlier but the defect is found later after production.

  • There could be a Missing defect, Wrong defect, and extra defect that lead to deviation in the output of the software.

FAILURE

The main reason for getting a failure is the incapability of software to do the required task and giving wrong output. There could be some reasons like human error, conditions related to the environment, wrong operations performed by the users, and misuse of the system.

Well, we do not need to dive deep into the other things just having a small knowledge about it would be sufficient.

How errors can be found?

Now the big question arises that how all of these errors can be found? How they are noticeable? What is the way to detect errors? For this, we have to understand a new thing called debugging. Whenever we write a program in any language or say we do coding and then try to run that code here includes a process called debugging. The objective of debugging is to find errors in coding and remove them. So now we will try to understand some common different types of errors in programming by having look at them so that we can get an idea to overcome and avoid them.

Errors are an integral part of coding. For example, I did the coding and made a program having some steps to solve a particular problem. The part code I wrote is called source code. Now the next step is to debug it. As we are familiar with debugging now it means we understood that it’s time when the computer is going to interpret a program or code or you can say compiling the code. Only debugging can find out errors that will lead to the crash of the system or will create other problems like not giving the desired output.

A Scientist named Edsger W. Dijkstra said programming or coding is the process of adding bugs in the program and debugging is the process of getting these errors and find ways to remove them. So now finally we will discuss a few types of programming errors and ways to avoid them which is the main topic of our article.

Types of error:

  • Syntax Error
  • Logical Error
  • Semantic Error
  • Arithmetic Error
  • Resource Error
  • Interface Error
  • Runtime or execution Error
  • Compilation or compile-time Error

Let’s have a detailed description of every error.

Syntax Error

In every programming language, we need the right sequence of grammar rules. Just as there is grammar for the English language and we have to follow rules of it to make proper sentences. In the same way, you have to follow some rules related to a particular programming language to write any instruction in a computer program. But if you violate the rule that governs language structure a syntax error occurs. In the English language, it’s quite fine if we don’t follow grammar rules in communication but the computer languages are quite strict in that aspect.

  • Generally, they are a small and very common type of error.
  • They are even single-digit and just stops the program execution.
  • An example is like missing a semicolon at the end of the line, wrong punctuation. Say the syntax of printing hello is print(‘hello’) and you forget to put the left side parentheses during writing the code then it will result in a syntax error.
  • They can be easily found and you can correct them.

How to avoid syntax error:

  • They can occur less frequently as the programmer gets more experience by practicing regularly.
  • You can avoid these errors by rechecking again your program step by step till the end line.
  • Try to be more aware of the syntax of the language.
  • As there is an increase in the proficiency of programmers the syntax errors tend to occur less in the program.

Logical Error

In general what you think about word logic. Is not it something related to the reasons behind something? Try to think it in way of calculation. Let’s understand it in a way, suppose I am going to make a program to find the sum of two numbers 2 and 3. Mathematically you know well that the answer will be 5 but what if during writing code you mistakenly not took the variable in which value of answer should be stored. So at that point how you would be able to get output. So logical errors are sort of errors that occur when you try to do some coding to get output but you don’t receive the correct output although you assume your program to be right.

  • It could be a type of error due to which you get the wrong output.
  • You can assume it as a type of misbehaving done by the program.
  • These types of errors don’t halt the execution of the program at all and even debuggers don’t give any warning.
  • They cannot be easily found out. So try to check out your calculation thoroughly.

How to avoid Logical error:

  • Before making any program do try to write down ideas, formula, function, or calculation way or sort of algorithm of that program.
  • Check the requirements in detail before making any program or software.
  • Try to use print statements more in your program that will help you out to get how the program is working.

Semantic Error

The word semantic is actually related to word meaning. Whenever a programmer tries to do the wrong use of program statements that sort of error arises. While making such sort of errors there is nothing produced at all. In simple language, we can say My refrigerator just drove a car to the USA. Is it making any sense? Same way in programming only a good programmer can detect such errors.

  • They are sort of errors that are alike the wrong words at the wrong place.
  • An example is when you try to divide any number by zero then what actually happens it just crash the system.
  • Making use of uninitialized variables is a sort of semantic errors.

How to avoid Semantic error:

  • These types of errors are not easy to detect but giving the program different inputs and try to check its response in that condition could be a good way to avoid such errors.
  • By choosing a good design and defensive programming could help to avoid such errors.

Arithmetic Error

They are usually a type of logical error in which you probably do the wrong mathematical calculations. you can even consider them under the category of runtime error.

  • These sorts of errors are easily avoidable.
  • An example is like division of any number by zero or you are not following the right order of calculation. Say the computation of 4-1*5. So the answer should be 4-5=-1. but when we do it the wrong way like 3*5=15 then it’s a sort of arithmetic error.
  • They can be easily found out and get corrected.

How to avoid the Arithmetic error:

  • To avoid them you should be aware of basic arithmetic operations.
  • Do try to avoid major mistakes related to parentheses or rules about the order of operation like BODMAS.
  • Try to do functional tests that include Zero or negative numbers.

Resource Error

Your computer system usually provides a fixed number of resources. You have to use them to execute programs. But what if your program requires more resources, in such cases resource error occurs.

  • When you do programming related to loops where you mistakenly write down code from which lop is not able to come out then such a situation is resource error.
  • For example, if you write a loop code like this for ( ; ; ) then such a loop will run forever.
  • Such sorts of errors are hard to find.

How to avoid Resource error:

  • Do try to use load testing applications and services that will help you to check out what will happen when multiple users try to run the same program at once.
  • They are sort of type of error also so do try to fix it early.

Interface Error

it’s an error that occurs when there is a discrepancy between the use of a program. I mean to say when you try your program to be used in the way A but that is not the way to use it. Such a situation is a case of interface error. Such types of errors occur mostly in software having standards.

  • These errors usually happen when there is a need for specific parameters to be set for API but it’s not provided that way.
  • They are also termed as Caller’s side error.

How to avoid Interface error:

  • If you have clear documentation of such errors and you can pass them back to the caller it could be a better way to handle such type of error.

Runtime or Execution Error

Such errors appear unexpectedly when the program is getting executed. Even the programmer and compiler don’t have an idea of these errors. Let’s say you are trying to access a type of variable that does not exist in your code at all.

  • The division of any number by zero is a common example of it.
  • Another example is like you have an array[5,4,6,7,3] and you know well it will contain elements and its storage will start from position zero and go up to 4 but when you try to access array value out of its bound say array[6] it will result in a runtime error.
  • They are also called execution errors.

How to avoid the error:

  • You can write a particular code that can execute when such an error condition arises like you can write a print statement that users should have to enter values only between 1 to 10 while using division or so on accordingly.
  • Do try to find out the reason for the error it could be either related to value or wrong input from your side then fix it like in the case of division by zero you can avoid it.

Compilation Error

Such sort of error is that one which is resulting due to compilation time. They could be syntax or semantic. When we do write code for a program we try to debug it so that we can get an idea about errors. The compiler results in these types of errors in form of messages. These messages are generated by the operating system. These errors are nothing just a piece of code to which the compiler cannot understand.

  • For example, if you wrote a program and in any instruction, you forget to put a semicolon at end of it you will get a message regarding such sort of error after compiling.
  • They can be easily found at compile time and you can correct them.

How to avoid the error:

  • Try to use steps to overcome syntax and semantic errors like don’t omit a semicolon, not use an uninitialized variable.
  • With time and good experience, compile-time errors get reduced.
  • Whenever such error occurs do try to understand its meaning and do find the line in which they occurred.

So for the conclusion, you can say that errors are an integral part of programming. But you have to try to spot them while doing the coding. Even we are aware of the fact that sometimes due to many reasons errors can occur in our program and that is no reason for embarrassment at all. Now we understood each and everything related to the error that can give us a better idea to avoid them and also we are now familiar with different ways to tackle them by knowing their type. Few points to keep in mind while making programs:

  • Do try to write down simple codes. Simple codes can be easily debugged and errors can be found easily.
  • Try to find different ways to make any program that will enhance your ability to inter-relating things.

Hope you all found this article quite informative to provide you with deep knowledge of everything related to programming errors. You can comment with errors you encounter commonly so that we can assure people more about them. don’t forget to do online exercises related to errors that will help you to differentiate errors. Do post your views so that I can find how much the article was beneficial for you all. You can also check out our articles on MySQL vs MongoDB.

Источник

В логике, философии и пр. науках, изучающих познание логическая уловка (англ. logical fallacy) — заведомо ошибочный способ обоснования тезиса, который в силу учёта психологических особенностей собеседника обладает убеждающим воздействием. Ошибочность обусловлена каким-либо логическим недочётом в доказательстве, что делает доказательство в целом неверным.

Содержание

  • 1 Виды логических ошибок
    • 1.1 Эквивокация
    • 1.2 Подмена слов, тезиса
    • 1.3 Использование ложных и недоказанных аргументов, утверждений
    • 1.4 Мнимая логическая связь
    • 1.5 После не значит «вследствие»
    • 1.6 Приписывание неделанных утверждений
  • 2 См. также
  • 3 Ссылки

Виды логических ошибок

Эквивокация

Эквивокация — ошибка, заключающаяся в использовании одного и того же слова в разных значениях в одном рассуждении. Основана на омонимии (от греч. homos — одинаковый и onyma — имя) — свойстве языковых единиц иметь несколько значений или выражать несколько понятий, никак не связанных между собой; напр., слово лук -растение и лук-ручное оружие. Аналогичным термином является Полисемия.

Сообщение об этой логической уловке можно выразить русской поговоркой «Федот, да не тот».

Имеется специальная Категория:Многозначные термины

Подмена слов, тезиса

Подмена Тезиса — (лат. ignoratio elenchi) — логическая ошибка в доказательстве, состоящая в том, что начав доказывать некоторый тезис, постепенно в ходе доказательства переходят к доказательству другого положения, сходного с тезисом.

Логическая уловка отражена в русской поговорке «Я ему про Фому, а он мне про Ерёму».

Использование ложных и недоказанных аргументов, утверждений

Другая логическая ошибка — «предвосхищение основания» (petitio principii). Она заключается в том, что в качестве аргументов используются недоказанные, как правило, произвольно взятые положения: ссылаются на слухи, на ходячие мнения или высказанные кем-то предположения и выдают их за аргументы, якобы обосновывающие основной тезис. В действительности же доброкачественность таких доводов лишь предвосхищается, но не устанавливается с несомненностью.

Обычно подобные лже-аргументы сопровождаются фразами: «Как абсолютно всем известно…», «Кто же будет спорить с тем, что…», «Аксиомой, не требующей доказательств, является то, что…», «Само собой разумеется, что…», «Каждому известо, что…», дабы рассеять возможные сомнения у простого слушателя.

Мнимая логическая связь

Логическая уловка, при которой мнимая, желаемая логическая связь выдаётся за истинную.

Логическая уловка выражена русской поговоркой: «В огороде — бузина, а в Киеве — дядька»

После не значит «вследствие»

Логическая уловка, при которой отождествляется хронологическая, временная связь с причинно-следственной.

Приписывание неделанных утверждений

Логическая ошибка, которая заключается в приписывании одной стороной другой, утверждений, которые на самом деле другая сторона не делала, но которые, якобы вытекают из её предыдущих утверждений.

См. также

  • Софизм
  • Список парадоксов
  • Проблема курицы и яйца
  • Сепульки
  • Омоним
  • Полисемия
  • Синонимы
  • Полемика
  • Риторика
  • Прокруст
  • Мышление
  • Некритичность
  • Догматизм

Ссылки

  • Теория Аргументации
  • Аристотель. Первая аналитика

Wikimedia Foundation.
2010.

Programming errors (such as syntax errors, logical errors, etc.), more commonly known as ‘Bugs’ in computing lingo, are the bane of any software developer. Since machines are increasingly being used in automated mode, with onboard embedded systems or computers controlling their functioning, a programming error can have drastic consequences.

There have been cases of space shuttles and planes crashing due to software bugs in embedded computing equipment. A single loophole left in operating system code can provide an entry point to hackers who can exploit the vulnerability, putting computer security at risk. Ergo, errors need to be taken very seriously as we increasingly rely on computers.

Let’s understand different types of errors in programming.

Types of Programming Errors

There are seven types of programming errors.

  • Syntax Errors
  • Logical Errors
  • Compilation Errors
  • Runtime Errors
  • Arithmetic Errors
  • Resource Errors
  • Interface Errors 

Let’s understand these errors one by one and how you can avoid them.

1. What is Syntax Error?

A syntax error in computer science is an error in the syntax of a coding or programming language, entered by a programmer. Syntax errors are caught by a software program called a compiler, and the programmer must fix them before the program is compiled and then run.

Syntax errors are different from errors that affect programs during run time. Many logical errors in computer programming do not get caught by the compiler, because although they may cause grievous errors as the program runs, they do conform to the program’s syntax.

types of programming errors

In other words, the computer cannot tell whether a logical error is going to create problems, but it can tell when code does not conform to the syntax because the understanding of that syntax is built into the compiler’s native intelligence.

Another aspect of understanding syntax errors is that they demonstrate how, unlike humans, computers cannot use input that is not perfectly designed. The lack of a period or comma in a sentence or command, or two swapped letters in a word, confounds the compiler and makes its work impossible.

On the other hand, human readers can spot typographical errors and understand them in the context of what they are reading. It is likely that as computers evolve through the coming decades, engineers may be able to create compilers and systems that can handle some types of syntax errors; even now, in some compiling environments, tools can auto-correct syntax errors on-site.

2. What is Logical Error?

A logical error is an error in a program’s source code that gives way to an unanticipated and erroneous behavior. A logical error is classified as a type of runtime error that can result in a program producing incorrect output. It can also cause the program to crash when running.

Logical errors are not always easy to recognize immediately. This is due to the fact that such errors, unlike syntax errors, are valid when considered in the language, but do not produce the intended behavior. These can occur in both interpreted and compiled languages.

For example, in PHP, when “if ($i=1) {…}” is incorrectly entered instead of “if ($i==1) {….},” the former means “become” while the latter means “is equal to.” The incorrect if statement would always return TRUE as assigning 1 to the variable $i. In the correct version, though, the statement only returns TRUE when the value of variable $i is equal to 1.

The syntax in the incorrect case is perfectly correct as per the language. So, the code would compile successfully without producing any syntax errors. However, during the runtime of the code, the resultant output may be wrong, thus showing that a certain logic error has occurred.

Logic errors tend to be hidden in the source code and can typically be harder to determine and debug, unlike syntax errors that are recognized at compile time.

3. What is Compilation Error?

Some programming languages require a compilation step. The compilation is where your high-level language converts into a lower-level language that the computer can understand better. A compilation or compile-time error happens when the compiler doesn’t know how to turn your code into lower-level code.

In our syntax error example, if we were compiling print(‘hello’, the compiler would stop and tell us it doesn’t know how to convert this into a lower-level language because it expected a ) after the ‘.
If there is a compile-time error in your software, you won’t be able to get it tested or launched.
Like syntax errors, you will get better at avoiding these with time, but in general, the best thing you can do is get early feedback when it happens.

Compilation happens across all files of your project at the same time. If you’ve made lots of changes and see lots of compiler warnings or errors, it can be very daunting. By running the compiler often, you will get the feedback you need sooner, and you will more easily know where to address the issues.

4. What is Runtime Error?

A Runtime Error is an error that occurs at the time of running or executing a program. When this error occurs, the program may hang or crash displaying an error message. There are many reasons for a runtime error, like when the program enters an infinite loop, it triggers the runtime error. Sometimes, it also occurs due to the user’s fault.

For example, a program requires a numerical value to process the result, but if the user enters any value other than the required one, say, an alphabetic character, the program may show a runtime error.

Runtime errors are particularly annoying because they directly impact your end user. A lot of these other errors will happen when you’re at your computer working on the code. These errors occur when the system is running and can stop someone from doing what they need to do.

Make sure you have good error reporting in place to capture any runtime errors and automatically open up new bugs in your ticketing system. Try and learn from each bug report so that in the future you can guard against this type of error.

Making use of frameworks and community-maintained code is an excellent way of minimizing these types of errors because the code is in many different projects, so it will have already encountered and fixed many issues.

5. What is Arithmetic Error?

An arithmetic error is a type of logic error that involves mathematics. A typical example when performing a division equation is that you cannot divide by zero without causing an issue.

Very few people would write 5 / 0, but you might not think that the size of something in your system might sometimes be zero, which would lead to this type of error.

ages.max / ages.min could return an error if either ages.max or ages.min were zero.
Arithmetic errors can generate logic errors as we’ve discussed, or even run-time errors in the case of divide by zero.

Having functional tests that always include edge cases like zero, or negative numbers is an excellent way to stop these arithmetic errors in their tracks.

6. What is Resource Error?

Sometimes, 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 causing the entire system to crash.

7. What is Interface Error?

Interface errors occur when there is a disconnect between how you meant your program to be used and how it is actually used. Most things in software follow standards. If the input your program receives doesn’t conform to the standards, you might get an interface error.

For example, an interface error might happen if you have an API that requires that specific parameters are set and those parameters are not set.

Unless handled correctly, interface errors will look like an error on your side when it is an error on the caller’s side. This can lead to frustration from both sides.

Programming errors are inevitable. Understanding common programming errors and learning how to deal with them is an essential skill that every programmer should have. Get better at spotting them early, but know you will never be perfect.

Hopefully, this article has prepared you for the different types of errors in programming and made sense of some of the most common error messages for you.

FAQs

What are the different types of programming errors?

The different types of programming errors are Syntax Errors, Logical Errors, Compilation Errors, Runtime Errors, Arithmetic Errors, Resource Errors, and Interface Errors.

What is the most common programming error?

While syntax errors are some of the most common programming errors, the good news is that they’re also some of the easiest to find and fix, as the compiler usually will identify the location of any of these errors. Syntax errors are the coding equivalent of grammatical errors.

Conclusion

An error resulting from bad code in some program involved in producing the erroneous result. There can be various reasons for these errors. Programming errors are broadly divided into seven types – Syntax Errors, Logical Errors, Compilation Errors, Runtime Errors, Arithmetic Errors, Resource Errors, and Interface Errors.

Recommended Reading

  • 10 Best Kids Coding Languages For 2023
  • Scratch – Best Tool For Kids To Learn Coding
  • Learning Geometry With Scratch – Basic 2D Shapes
  • Learn To Create Line Patterns in Scratch Using 2D Shapes
  • 5 Interesting Games in Python That Kids Can Make
  • Learn Math With Python
  • 5 Easy JavaScript Projects for Kids
  • Cool Apps That Kids Can Make
  • Best Mobile App Development Tools for Kids

You May Also Like

pascal's triangle

Pascal’s Triangle – Definition, Pattern & Examples

Table of Contents What is Pascal’s Triangle?How to Create a Pascal’s Triangle?Pascal’s

science fiction books for kids

Best Science Fiction Books for Kids (Must Read!) – 2023

Table of Contents Best Science Fiction Books for Kids1. A Wizard of

what is binomial theorem

What is Binomial Theorem – Formula, Expansion & Examples

Table of Contents What is Binomial Theorem?Binomial Theorem Expansion ProofExamples of Binomial

When programming, there can be errors. An error is an unexpected output of the program. These errors can affect the proper execution of the program. Therefore, it is necessary to remove all errors. An error is also called as a bug. The process of identifying errors and fixing them is called debugging. Each programming language has a specific syntax. The programmer should follow the correct syntax to write programs. When there is syntax mistake, it is known as a syntax error. A syntax error occurs at compile time. The error that occurs at runtime is called a runtime error. Array out of bound, diving by zero, accessing memory that is not available are some examples of runtime errors. When writing a program, there is a sequence of steps to follow to solve the problem. This methodology is called an algorithm. If the logic of the program is wrong, it will give incorrect output.  That kind of an error is known as a logical error. This article discusses the difference between a syntax error and a logical error. The key difference between syntax error and logical error is that, the syntax error occurs due to an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language while logical error is an error that occurs due to the fault in the program algorithm or the logic.

CONTENTS

1. Overview and Key Difference
2. What is Syntax Error
3. What is Logical Error
4. Similarities Between Syntax Error and Logical Error
5. Side by Side Comparison – Syntax Error vs Logical Error in Tabular Form
6. Summary

What is Syntax Error?

Generally, the programs are written using high-level programming languages. C, Python, Java are some examples of high-level programming languages. The source code is easy to read and understandable by humans. These programs are not understandable by the computer. The computer only understands machine code. Therefore, the high-level program is converted into machine code using a compiler. Each programming language has own set of syntax to write the program. The programmer should write the program according to the correct syntax. If not, it will cause an error. This error type is known as a syntax error. This error occurrs at the time of compilation.

It is easy to identify and remove syntax errors because the compiler displays the location and type of error. When there are syntax errors, the source code will not have translated into the machine code. Therefore, for successful execution, the programmer should fix the syntax error specified by the compiler. Some common examples of syntax errors are missing semicolons, missing curly braces, undeclared variables or misspelled keywords or identifiers. If the programmer only writer int x without the semicolon, it is a syntax error. Misspelling the ‘int’ is a syntax error. Therefore, it is necessary to follow the syntax relevant to the programming language when writing the program. The program will not compile until the syntax error is fixed. In an interpreted language, a syntax error is detected during program execution, so it might be harder to differentiate syntax errors from other errors.

What is Logical Error?

A program is written to solve a problem. Therefore, it flows an algorithm to solve it. An algorithm is a step by step procedure to solve a given problem. The errors occur due to an algorithm fault is known as a logical error. A program with logical error will not cause the program to terminate the execution but the generated output is wrong. When a syntax error occurred, it is easy to detect the error because the compile specifies about error type and the line that the error occurs. But identifying a logical error is hard because there is no compiler message. The output is wrong, even the program executed. Therefore, the programmer should read each statement and identify the error on his own. One example of logical error is the wrong use of operators. If the programmer used division (/) operator instead of multiplication (*), then it is a logical error.

Difference Between Syntax Error and Logical Error

What is the Similarity Between Syntax Error and Logical Error?

  • Both Syntax Error and Logical Error are categories of errors in programming.

What is the Difference Between Syntax Error and Logical Error?

Syntax Error vs Logical Error

A syntax error is an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language. A logical error is an error in a program that causes it to operate incorrectly but not to terminate abnormally.
 Occurrence
A syntax error occurs due to fault in the program syntax. A logical error occurs due to a fault in the algorithm.
Detection
In compiled languages, the compile indicates the syntax error with the location and what the error is. The programmer has to detect the error by himself.
 Simplicity
It is easier to identify a syntax error. It is comparatively difficult to identify a logical error.

Summary – Syntax Error vs Logical Error

Errors might occur while programming. There are different types of errors. Runtime error occurs at runtime. Some examples of runtime errors are diving by zero, accessing memory that is not available. Syntax errors occur due to syntax mistakes. The logical errors occur due to a fault in the logic of the program. The difference between a syntax error and logical error is that the syntax error occurs due to an error in the syntax of a sequence of characters or tokens that is intended to be written in a particular programming language while a logical error is an error that occurs due to the fault in the program.

Reference:

1.PGC Lectures: Programming Errors & Types, Syntax Error, Runtime Error, Logical Error, Online Learners, 8 Jan. 2017. Available here  
2.“Syntax error.” Wikipedia, Wikimedia Foundation, 17 Feb. 2018. Available here
3.“Logic error.” Wikipedia, Wikimedia Foundation, 27 Feb. 2018. Available here

Понравилась статья? Поделить с друзьями:
  • What is http error codes
  • What is http 500 error
  • What is error in sql syntax error
  • What is error 403
  • What is eof error