from some articles I read on general programming concept. I was made to know that "syntaxs are the formal rules that governs the construct of valid statement in a language" while "semantics are set of rules that give meaning to a statement of a language". from the defination of semantics, I feel it is similar to logic, if not, then please I want to know the difference between logical error and semantic error?
There seems to be lot of confusion around the definition of these terms, but here's my understanding:
Syntax relate to spelling and grammar.
Logic relate to program flow.
Semantics relate to meaning and context.
If the code fails to execute due to typos, invalid names, a missing parenthesis or some other grammatical flaw, you have a syntax error.
If the syntax is correct but a piece of code is (inadvertently) never executed, operations are not done in the correct order, the operation itself is wrong or code is operating on the wrong data, you have a logical error. Using a wrong conditional operator is a common example, so is inadvertently creating an infinite loop or mixing up (valid) names of variables or functions.
If both your program logic and syntax is correct so the code runs as intended, but the result is still wrong: you likely have a semantic error. Confusing a metric input value for an imperial value will get you there. Nothing wrong with the program, except that miles and kilometres don't add up, so your area calculation throws out the wrong number. Having a race condition is another common example.
The answer here depends on the book you are reading or the class you are in. In many areas of Computer Science, there is absolutely no difference between a Semantic Error and a Logic Error. Both mean that the program compiled, but the output was wrong. Just as often, they mean two different things. A simple example is intending to use X+1 in your program, but you typed X-1. That is a Logic Error. If you typed X+true, it would be Syntax Error if the language allowed it to pass through the parser, but the result of X+(boolean true) wasn't the same as X+1. Personally, when it comes to poorly defined terms such as this, I let people define them how they like and just remove the errors from my programs, regardless of what kind of errors they are.
Basically differentiating semantic errors and logic errors is contradictory as, first both in programming produce an result that is not to the expected function of the program and secondly logic errors result in semantic error as the program runs against expected functioning.
Just Google it thousands of answer will be in front of you with brief.
Semantic error is related to the meaning of something. it mean that it is a violation of the rules of meaning of a natural language or a programming language , suppose we are using the programming statement improperly ..the semantic error will be detected at compile time.
and the logical error is that Errors that indicate the logic used when coding the program failed to solve the problem. The logic error will not cause the program to stop working but our desired result will not be get.
if you want to see the example go to this site.....
http://newtutorial2012.blogspot.com/2012/07/differentced-between-synataxsemantic.html
Related
Ruby and some other languages have a very convenient feature: symbols. They look like in-place constants. Now I wonder if the following approach by simulating symbols in PHP with an at sign before an unquoted string is a valid approach.
$array = [#key => "value"];
echo sprintf("%s PHP symbols with a %s\n", #testing, $array[#key]);
I understand there are certain drawbacks against formal constants and the like, which are same as for Ruby's symbols: consider typing errors. Are there any other considerations against using this approach?
If by "valid" you mean "can be run", then yes, it is a valid approach (but by that standard, it is also valid to make all of your strings into HEREDOC's). But simply because PHP will accept the syntax, does not mean that the syntax is without problems.
The first I can think of are that
You are actively suppressing an error, which costs processing time
Your co-workers will need an explanation as to what is going on, which costs developer time
You are working against the natural definitions of the language (PHP simply isn't Ruby)
Since you have to use a sigil for variables anyway, you're not actually cleaning the code.
You are suppressing an error (a notice, to be exact). not only this costs processing time as mentioned in cwallenpoole's answer, but also the error is there for a reason. The reason is:
Notice: Use of undefined constant hello - assumed 'hello' in ...
You are relying on some constant being undefined - which is exactly what the notice is trying to tell you. If a constant of that name is defined, you will grab its value instead.
In Ruby, :__LINE__ is something quite different from __LINE__. The former is a symbol - it equals itself no matter where you use it. The latter is a number, and a magical variable that changes its value on every line. In PHP, #__LINE__ is the same as __LINE__, because there is no error to suppress. Oh, and there's one special "symbol" that is extra-fun to debug: #exit, AKA #die.
In Ruby, you can use all sorts of symbols including operators and keywords. These (and many more) are all valid: :+ :* :< :<< :[] :[]= :while :case :x=. With a pair of parentheses, you can even use symbols like :case= and :while=. In PHP, none of these work. You'll end up with a parse error. It won't even be suppressed. The only exception is #[] in PHP 5.4, which produces an empty array. On the other hand, lots of PHP expressions are not valid Ruby symbols: #(1+1) === #2 #1 == #'1'
Ruby's symbols are not equal to anything else. This is the purpose of their existence. Sure, they have some nice properites like to_s and to_proc, but their original purpose is to serve as identifiers separate from any possible user input. This is sorta nice for example if you are using symbols to represent tokens in a lexer stream, such as [:lparen, 1, :plus, "rparen", :rparen]. In PHP, undefined constants are strings. In Ruby, ?test != "test". In PHP #test === "test" (assuming you dindn't define a constant named "test" to equal something else).
you can't even assume non-magic constants won't change. You can't even attribute to malice what can be explained with bad coding. Nothing like that is of worry in Ruby:
//in library code:
$this->status = #done; // bad
//outside library code:
define('done', "no"); // very bad
define(#done, "yes"); // even worse
echo #no; // prints "yes"
//in library code:
if($this->status == #done){
//won't execute
}
echo #die;
echo "this won't get printed!";
You shouldn't rely on constants being undefined, and you shouldn't use error suppressing to hide the error messages telling you that. You shouldn't use special notation to pretend two things are not equal when they are. Also, can you trust the users of your library to not redefine constants at runtime?
Warning:
The following answer contains analogies that are meant, purely to illustrate a point. Under no circumstances do I mean to even suggest you contemplate the possibility of someone (you or anyone else) actually sitting down and doing the things I mention. That way madness lies
Though other answers have explained the main issue with using #<str>, It supressing a notice, it's important to stress this a bit more.
When using the supressing # (of death) the notice does not magically dissapear it is still being issued. After a while logs will get clogged with notices, making it harder to find that one fatal error that could be in there. Even if there is no fatal error, it still slows the code down.
Why encourage people to write code that throws notices? Just because you like the ruby syntax? come on, if you don't like a language, don't use it. I know: legacy code, you have to... well then, do it, don't try to make it feel and look like Ruby. They're not the same language. Everything that reminds you of the fact that you're working with a different language should be seen like a tool. Different languages require different mindsets, and different ways of thinking about a problem.
Imagine writing Lisp, but change the syntax to SQL queries. How much bad code will that generate. The syntax forces you into an SQL mindset, whereas you should be thinking in functions.
But for God's sake, don't that way madness lies!! It's a fools errand, it's even worse than parsing HTML with regex. It'll make even Cthulhu cry like a little girl
Oh, and # not being used to supress errors once it's in common usage? Do you really believe that? So you expect a lot of people to write bad code, until some IDE plugin is released that doesn't complain about the abuse of the # sign. And then, you expect the PHP contributors to take notice, and find a new operator to supress errors?
Honestly. I don't want to be rude, but that's like expecting Microsoft to release the source of windows8, because some people have gotten used to linux being open source.
Another thing: As I said, suppressing notices isn't going to help you when debugging the code. It's well known that PHP has way to many functions (and reserved keywords) in its core/global namespace. If you, and your co-workers get in the habit of abusing the # operator, you could just end up with code like this:
$foo[#die] = [#exit, #constant];
Have fun debugging that onholy mess of unclear errors. Honestly...
The key in your code would be seen by PHP as an unknown constant.
In most languages this would halt the compiler, but PHP mutates it into a string in an effort to keep running. It throws a warning, but keeps going anyway. This is just bad, and you really don't want to be doing it, much less doing it deliberately.
# in PHP is for suppressing errors. It does nothing else.
Your #key will still be bad practice just as key would be and would function in exactly the same way, but the # will hide the error message that would normally be generated.
Using # error suppression in PHP is bad practice for a whole bunch of reasons (‡ see note below), but using it as a way to hide deliberately bad code is terrible. Please don't do this.
The fundamental point here is that you're using PHP, so you should write PHP code. Trying to write Ruby code in PHP is never going to work.
You should work with the language you're using, not against it.
‡ For some thoughts on why error suppression is bad practice, you may want to read this: Suppress error with # operator in PHP
One final thought: This thing of PHP converting unknown constants to a string exists in the language purely for legacy compatibility reasons; it's one of the really awful bits of bad language design that date back to the early days. A lot of the other bad stuff from early PHP has been deprecated in recent versions; this hasn't yet, but there's no good reason for it still to exist, so I kinda hope they find a way to deprecate this "feature" too. If they do, that will instantly stop your idea from working, regardless of any merits it may have.
PHP defines two SPL exceptions for invalid keys:
OutOfRangeException: Exception thrown when an illegal index was requested. This represents errors that should be detected at compile time.
OutOfBoundsException: Exception thrown if a value is not a valid key. This represents errors that cannot be detected at compile time.
As PHP isn't a compiled language the distinction between compile-time and run-time seems strange and thus I am finding it hard to understand which exception to use when.
Currently my understanding is that one should throw...
... OutOfRangeException if the key is fundamentally and inherently malformed, e.g. if an array is passed as a key.
... OutOfBoundsException if the key is generally okay, but isn't in some boundaries, e.g. if 100 is passed but 50 is the maximum key.
Is that understanding correct?
While PHP doesn't have a classic "compile time" (or a compiler that do a lot of static checks for that matter) I'd treat "compile time" as "rather static stuff I did wrong when writing the code" and "run time" as "my logic, input or validation was off at some point".
So my suggestion would be to treat it like this:
"Compile Time" / "OutOfRangeException": The error can always be fixed in the source code without or with very little logic.
I always take numbers from 1-10 and you put in 11
"Run Time" / "OutOfBoundsException": The error is due to wrong use at runtime.
You created me and told me to take values from 1 to 5 then you put in 7. Doesn't compute
or
You request an index that is not there because you didn't put it there like you should
Sample:
I'd expect an SplFixedArray to throw an OutOfBoundsException because it's size is dynamic and can chance at runtime while I'd expect something like a Calender::getMonthName to throw and OutOfRangeException because the number of month are definitely fixed at "compile/write" time.
Array object sample:
Say $array is an object that implements ArrayAccess you could throw an OutOfBoundsException in these circumstances:
$array['bar'];
$array[7];
As the values are what you could expect for ArrayAccess but it doesn't make sense in the case of an SplFixedArray(5). Alternatives would be DomainException or maybe RangeException
An OutOfRangeException in these cases:
$calendar->getMonth(15);
As putting an array or a new class there is definitely some bigger logic flaw in the code that usually results from a simple "oh, i put in the wrong variable" error by a programmer. An (maybe preferable) alternative would be UnexpectedValueException and good old InvalidArgumentException.
For cases like:
$array[array()];
$array[new StdClass];
some of the alternative exceptions seem more fitting.
Comparisons with the Java world on which exception to use when are not always applicable as Java Developers have an additions issue to deal with.
Checked/Unchecked exceptions. With many people arguing that everything that isn't a runtime exception has very limited use in Java / should not be used much internally) those names have lost some of their original meaning and intent.
My own take on this is:
LogicException
use for any mistakes the developer did, e.g. mistakes when programming/assembling the application. Those will hopefully be catched when the developer is running his/her UnitTests (which would then be the equivalent of Compile Time). Those exceptions should never occur on the production site as they are errors in the software as such.
RuntimeException:
use for any mistakes the user did or that result from invalid data put in the application at runtime. These are errors that might be anticipatable but not fully preventable by UnitTests, e.g. those can happen on a production site. Those exceptions could be stemming from incorrect usage or programming errors.
OutOfBounds
is IMO effectively what Wikipedia defines as Range of an Array in Range in Computer Programming, namely:
When an array is numerically indexed, its range is the upper and lower bound of the array. Depending on the environment, a warning, a fatal error, or unpredictable behavior will occur if the program attempts to access an array element that is outside the range.
In other words, when you have an array with indices [0,1,2] anything but [0,1,2] is out of bounds. Note that Bounds can also apply to other data types as well, e.g. trying to access the 7th character in a 5 character string would also be OutOfBounds.
OutOfRange:
this one is a tough cookie. In C++ OutOfRange is a generic exception extending LogicException (just like in PHP). I am not sure if the example given is easily translatable to PHP code though or my definition of Compile time above. Mainly because no one would first init a new Vector(10) and the immediately try to access it at(20).
In Java OutOfRange seems to refer to Range in the mathematical sense
The range of a function is the possible y values of a function that result when we substitute all the possible x-values into the function.
One reference I could find has it extending RuntimeException though, so I guess looking into other languages wont help to solve this mystery. There is also an open bug report about the SPL Exceptions in general, stating that
OutOfRangeException (value is out of range) is LogicException, should be: RuntimeException
But if this is correct, then how is OutOfRange different from DomainException? And if your own definition is correct, then how is OutOfRange different from InvalidArgumentException?
To cut a long story short: I dont know what OutOfRangeException is supposed to be for.
The answer to your question is quite elusive to me also. However, here are some things to think about:
If an array is passed in when we are expecting a valid array key, we also have InvalidArgumentException because it is not the proper argument type.
We could also throw a DomainException because arrays are not in the domain for array keys.
In php, you generally can't detect types at compile time because of late static binding. They purposefully delay binding of variables to runtime.
How I handle this situation:
Throw an InvalidArgumentException if a variable is passed in to any function where it the argument is not the correct type. I still do this when working with arrays.
Throw an InvalidArgumentException if null was passed in when it shouldn't be. This one really could be a lot of things because null isn't typed. To keep error code checking simple, I simply stick with the invalid argument.
Throw OutOfBoundsException when an index is not in the correct range, just as you suggested.
Throw BadFunctionCallException if a user-supplied function as a parameter does not have the correct form. If your structure inside is an array, it makes sense that they could pass in a function to modify it, so this comes up occasionally.
Generally, I can use just these three exceptions to represent all errors that occur outside of special resources (Network and database connections would be special resources). The third one seems to have been cropping up more often, but primarily I've just dealt with the former two.
It is quite simple:
OutOfRange mean "Your requested key is not within the index of a set defined in code."
OutOfBounds means "Your requested key is not within the index of a set defined by loaded configuration."
The confusion in this case comes from a couple of factors. First, PHP is in fact compiled into bytecode. There are several execution environments where this compiled form persists in a relatively permanent form on the server. However, the OutOfRangeException/OutOfBoundsException issue is not about that, it's about a categorization error made by the people who documented these specific exception classes.
Since PHP is dynamically typed, it's often impossible to actually check ranges and even types at compile time. The manual states that OutOfRangeException should be raised at compile time and OutOfBoundsException should apply at runtime, which is an erroneous distinction to make in this context.
Both manual entries use unclear language of what an illegal index means, but looking at the usage of their parent classes gives some clues: LogicExceptions are extended by classes like DomainException, InvalidArgumentException, and LengthException, whereas Runtime exceptions are things such as UnexpectedValueException, OverflowException and UnderflowException. From this pattern one can infer that OutOfRangeException should probably be applied to illegal key types, and OutOfBoundsException should apply to index values that are of the correct type but are not within the bounds of their container.
There was some discussion on the PHP dev list about these categorizations being wrong, but the issue goes deeper than that. In practice, both exceptions can only actually be are raised at runtime. You can use the vagaries of the documentation to squeeze out a distinction between invalid key types and invalid index values, but at this point we're talking about a bug in the PHP documentation.
If you get an unexpected index. ie you expect a string but end up with an integer or vice versa. Then you should throw an UnexpectedValueException exception.
If you get a proper type of index but it doesn't exist. Then raise a warning (trigger_error) and proceed on. This is not expected to stop programming flow.
If you have an object that is iterable or supposed to be iterated over a range and it reaches it's limit (ie the end of a file), then you should throw an OutOfBoundsException.
Anything else is a candidate for OutOfRangeException.
In layman's terms. An OutOfBoundsException is something normal. It's not that serious. It's something that happens often and should be taken care of. it can be used by iterators to keep reading data till there is no more to read. It is a logical error. Made by someone using the code not by someone writing the code.
An OutOfRangeException is something serious. Someone should look at the source code. Someone should find out what happened. This is important. Theoretically this was never supposed to happen. Call 911. It is a compile time error. Made by the dummy programmer.
Out of range exceptions are written by programmers to guard against mistakes by other programmers. Or maybe yourself in the future. If you feel like something like that could never happen then use Out Of Range. Use Out of Bounds for something likely to happen.
Ok, this might be a very noob question, but I find that PHP Documentation on that and several Internet Searches hasn't give me any idea about that.
When should I use try-catch blocks to improve my application?
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
I read someone else saying that we should use it only on unexpected errors (wait what? unexpected? if they are unexpected errors how could I prevent them with try-catch? should I put all my application code inside a try block?).
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this I found a nice SO question about performance).
It seems to me that this topic is very strange and confused. Could someone lights me up?
It seems to me that this topic is very strange and confused. Could someone lights me up?
Definitely. I'm not a PHP user, but I might have a little insight after having worked with try/catch in ActionScript, Java, and JavaScript. Bear in mind though, that different languages and platforms encourage different uses for try/catch. That said...
The only times I'd recommend using try/catch is if you're using a native language function that
Can throw an error/exception
Does not give you any tools to detect whether you're about to do something stupid that would cause that error/exception. eg: In ActionScript, closing a loader that is not open will result in an error but the loader doesn't have an isOpen property to check so you're forced to wrap it in try/catch to silence an otherwise totally meaningless error.
The error/exception really is meaningless.
Let's take the examples you list and see how they square with that list.
I read someone saying that we should use try-catch blocks only to prevent fatal errors.
In the case of AS's loader.close() function, this is good advice. That's a fatal error, and all from an otherwise trivial misstep. On the other hand, virtually ALL errors in AS will bring your application to a halt. Would you then wrap them all in try/catch? Absolutely not! A "fatal error" is fatal for a reason. It means something terribly wrong has happened and for the application to continue on in a potentially "undefined" state is foolhardy. It's better to know an error happened and then fix it rather than just let it go.
I read someone else saying that we should use it only on unexpected errors
That's even worse. Those are presicely the errors you DON'T want to silence, because silencing them means that you're never going to find them. Maybe you're not swallowing them, though... maybe you're logging them. But why would you try/catch/log/continue as though nothing happened, allowing the program to run in a potentially dangerous and unexpected condition? Just let the error kick you in the teeth and then fix it. There's little more frustrating than trying to debug something that's wrong in a program that someone else wrote because they wrapped everything in a try/catch block and then neglected to log.
Others simply say that try-catch blocks should be used everywhere because they can be also extended (extending the Exception class).
There's potential merit to this if you're the one doing the throwing, and you're trying to alert yourself to an exceptional situation in your program... but why try/catch your own thrown error? Let it kick you in the teeth, then fix it so that you don't need to throw the error anymore.
Finally someone says that PHP try-catch block are totally useless because they are very bad implemented. (On this i find a nice SO question about performance).
Maybe so. I can't answer this one though.
So... this might be a bit of a religious question, and I'm certain people will disagree with me, but from my particular vantage point those are the lessons I've learned over the years about try/catch.
Different people will tell you different things. But this is what I think, specifically in the case of a web application.
Your whole page should be in a try/catch that displays an error message to the user. The error message shouldn't tell the user what happened in detail because thats a security concern. It should record information about the error into a log file.
The other case is where something could go wrong in the normal operation of affairs. PHP is not very exception happy so this may not happen very much. Basically, if you run into a function that throws an exception when it fails, you can catch the exception and do something else in that case.
In general, your question is like asking how you would use a hammer to improve the qualify of a house. Use exceptions to help you implement particular behaviors. Don't look for places to use exceptions.
I think it's simply a matter of preferences, but from my experiences, I'd encourage you to use them as much as possible.
In application we currently develop at work (using Zend Framework if it matters), we use one single try..catch block to catch all exceptions throughout the application which are shown to user as, for example, error 500s and exception is logged with more information to database. I, personally, love this approach in case of PHP application as exceptions are extendable and you can basically write whatever functionality you need.
I predominantly use Try/Catch around database calls...especially inputs, updates and deletes etc.
I sometimes use it around complex data processing with arrays and loops using dynamic data and arrays where there is a chance something might go wrong, ie: missing array elements or something (I normally check for stuff like that though).
I also use them around operations over which I don't have complete control such as importing data from an external or foreign data source where there could be problems with the data or accessing the source file.
I think what is meant by "Unexpected Errors" is where you can't prevent problems through good programming practices such as checking if a file exists before "including" it, Some problems you CAN anticipate so use good practices to prevent them. Don't just leave them to chance by wrapping them in a try/catch.
Use good programming practices instead as you should do everywhere. Don't use try/catch as a lazy shortcut for everything, everywhere. That's major overkill.
I agree with #scriptocalypse. In fact I only use try/catch blocks in PHP in 2 kind of situations.
If it's possible that some external (not inside my code) issues or DB errors may take place:
Getting data from another source (eg. curl)
Getting data from files
DB-Exceptions
If I work inside another system, like a CMS or similar and I want to override a certain behavior. For example I don't want an Exception being thrown but the exceptions message being returned to the view.
You cant put try catch blocks everywhere.
However during application testing, exceptions generated should alert you to places where you need try catches. This is one reason why you should run thorough testing of you application/code.
If you see a place where you think you need it, i would put one in.
EDIT: ok you CAN put them everywhere, but you need some sense as to where to put them in your code.
I normally put Try and Catch around areas in the code that have external forces acting on it that I have no control over. For example, Opening and reading external files.. you have no control that at some point in the reading of the file, the file becomes corrupted or something else happens that you can not control like the file server dc's or something
I was hoping you guys could help me on this one: how to handle errors and what to return?
What I do, most of time, is make my functions/methods return two possible values. The intended value in case of success and FALSE in case of failure. This way I can use:
if(function()) { ... } else { ... }
I don't like to use exceptions because, generally, they print something and interrupt the functioning flow of the application. Of course, I can make them to return something and show an alert with the error. But it's too much work. And I don't like Pokemon so much to try to catch them all. (Awsum topic, btw)
Another thing I'm concerned about is to code something "error-handling" driven. As we know, users can do almost anything to cause an unexpected situation, and to code expecting these errors is too tiring and frankly, is making me paranoid. XD
I apologize for any english mispelling(I don't write too often).
Thank you for reading this question. :D
PS: I read about defensive programming and the other questions but they don't quite answer my doubt.
Maybe you won't find my answer useful because I'm not a php developer, anyway I will try to give you common hints as error handling debates are common in any programming language.
1) First try to avoid the actual need for error handling. This does mean try to code in a way that error conditions are few as possible. A simple example: it's common sense that trying to clear an empty collection should not raise an error.
2) Distinct what is a supported failure than an unsupported one. A supported failure is an error condition that you actually want to track and handle as part of the program logic. An unsupported failure would be an error condition that's actually a code error. For example: you are trying to lookup an element in a map and it's part of the logic of your program that the specific element should be there. There's no sense to add code to test if the element was there and raise an error if it wasn't: you made the assumption it was there.
After you have understood these two points, I'm pretty sure you'll understand why exceptions are so useful to produce cleaner and more efficient code. The trick is: make your code to raise as few exceptions as possible (again: distinct supported and unsupported error conditions to choose what exceptions are actually needed) and catch them only at the most external scope, where the user of your application interact with it and 1)should be warned, 2)should decide what to do. Programmatically catch an excpetion without user interaction is, most of the times, a bad thing because it makes the dev think that catching exceptions is efficient just like conditionally do something (if-then-else) when an error condition arise when this is not the case. Exceptions won't cause any overhead to your application until they are thrown.
Have you tried working with PHP's error logging tools? http://php.net/manual/en/book.errorfunc.php
You can then use things like error_log() to shoot your custom errors to whatever log file you want.
You should consider using Exceptions. They don't print anything if you don't want to. At least this would be a better separation of your actual code and error handling.
You are right, having a function return a value or return false on error is not the best style (yes I know that this is probably done a lot).
If you want to learn more about good coding practice, I suggest to read Clean Code by Robert Martin.
I have turned on error_reporting(E_ALL) and run this code:
$topic_id = (int) safe_query($_GET['top_id']);
if($topic_id > 0)
include("topic.php");
And get this error: Notice: Undefined index: top_id. Is it that bad what I do? If yes then why? Should I check if $_GET['top_id'] isn't empty before I give its value to $topic_id? Why? Thank you.
One of the reasons why I do it is to prevent unexpected behaviours.
Code should always reflect the intention of the programmer. If a behaviour depends on some mysterious process in the background, eventually it will come and bite you in the ass when you are knee deep within bugs and debugging.
Traditionally, attempt to access an array with a key that doesn't exist causes a crash (probably in unmanaged environment) or an error. PHP silently 'fixing' this in background is great for beginners, but bad for debugging. Your code will work, but may give you unexpected result.
Take for example, your code. Say the calling page forget to specify the top_id, or misspelt it as topid, and PHP goes on its merry way. It didn't include topic.php, and nothing happens. The code works fine. PHP doesn't complain. What's wrong?
Now, your code is short. What happens when it is longer? Nested deep within many lines, between different functionalities? For your case it isn't a big deal, but when doing complex array manipulation it will make debugging harder.
I understand the question now. I'd suggest using isset just to be safe. I'm assuming you don't have a topic_id that is 0.
It's not really a problem here, since you only take action on it if it's set anyway. However, you're just lucky that the unset value evaluates to false. Also, it'd be annoying to continue having it give you the warning. You'd probably be best suited by doing what others have suggested, checking if it's set before using it. It might be easiest to just set up a function that does that, especially if you're going to be checking a lot of GET parameters.
Whatever you do, don't just turn the warning level down to suppress the warning; in this case, it doesn't hurt to assign from the unset variable, but in the future it could indicate an actual error.
"And get this error ... Is it that bad what I do?"
Well, it's not giving you an Error. It's giving you a Notice. Notices are "ignored" (that is, not echoed) on production servers.
Essentially, PHP is telling you what Extrakun is saying in his answer. You should take notice to a potential mistake that could lead to a real error later.
So, "Is it that bad what I do?" ... maybe not. But, then again, PHP is also not giving you an error. It is giving you the right amount attention that the code segment deserves - a Notice.