Traps as exceptions - mumps

The trap mechanism in Mumps has similarities to the exception mechanism in many other language.
Most examples I have seen of trap usage is for catching unintentional errors.
Is there also a way intentionally trigger an error, which can be caught by a trap, in a way that is similar to throwing an exception?
I am working with GT.M V7.0. I’m learning about traps from here:
http://tinco.pair.com/bhaskar/gtm/doc/books/pg/UNIX_manual/ch13s06.html

You can do this by setting the $ECODE variable.
See also https://docs.yottadb.com/ProgrammersGuide/errproc.html#ecode.
This is YottaDB but I think it will work for GT.M too.
SET $ECODE=",U13-User defined error trap,"
A simple thing that should work too: S X=1/0

Related

what is the diffrence between error and exception

when i search this on google then it show that error means compile time error and exception is runtime error? but i think that it is not that so....
That is generally correct. Although the terms are colloquially interchangeable in many domains.
An Error, also known as a compile-time error, is a statement of fact. (Or NOT fact) The compiler is unable to compile the output.
Technically an error is a state in code that has raised an exception in the compiler's runtime :)
An Exception is raised at runtime and is the result of an exceptional combination of values.
Because an Exception is raised at runtime, we can generally write code to catch and handle or workaround an exception within your script or code. An Error prevents the code from being compiled and thus executed at all, so our only option is to modify the code to resolve an Error.
A compiler may perform syntax and sometimes type checking to ensure that the code follows a set of pre-determined rules and can be compiled into executable statements, but it is not until invalid values are passed into those statements that an Exception can occur, that is harder for a compiler to do and so is generally only detected at Runtime.
Some advanced or specialised compilers may perform checks against common values and as a programer you can write unit tests to try and pre-emptively detect exceptions before releasing your code.
Exceptions and Errors are the same things. Somewhere in software history, someone came up with the phrase “Exceptions are exceptional”. That sounds catchy but it doesn’t translate to Exceptions and Errors. If you go that route then who decides what is Exceptional? It is very subjective an error for one context could be exceptional to one and not to another. Exceptional and Exception are very different words. Someone apparently thought the catchy phrase enforces the idea that there is a difference.
They are the same thing. I’m not a Java developer and I realize it has different classes for each but in the .NET world they are the same thing. The preferred error handling framework in .NET is the Exception class. It doesn’t care what you want to call it, an error or an exception. Nor does it care if it is exceptional or not. It is just a vehicle for communicating error information. You can communicate the severity of an error by creating and using classes that inherit from Exception.
The Source of my information is here:
Cwalina, K., Abrams, B. F., Barton, J., Icaza, M. de, & Hejlsberg, A. (2020). Framework design guidelines: Conventions, idioms, and patterns for reusable .net libraries. Addison-Wesley.

why the exception will throw even the syntax of code is correct?

I have come across exceptions many times especially checked exceptions.When the syntax of the code is correct why should we have to put in try-catch block.
if we don't put into try-catch block it will give error.
please explain me about checked exceptions.why would some code will throw exceptions even the syntax is correct.
Expections have nothing to do with illegal syntax. Excpetions are used in cases, where an error happens that can't be known about when the code is written or compiled, one example would be that there is no more memory available.
For languages which are compiled (e.g. Java) Expections are thrown while the program runs. On the contrary, syntax errors are handled by the compiler, at compile-time.
Syntax isn't the only resource for Exceptions. Invalid indexing, Mathematical errors, Connection issues, Db structure incompatibilities do cause Exception too!
Unless you are not handling a spesific type of Exception, the purpose of catching general Exceptions is to manage them. If you are not intented to manage them, you may not catch them at all. But whatever the situation is DO NOT SUPPRESS Exceptions. If you have to handle some erronous situation use logical locks.
Exceptions are for exceptional situations only, and should not be used for data validty. Exceptions are way too much costly for that.
Exceptions has nothing to do with syntax errors. An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons.
For example, you can see the exceptions in following reasons:
Invalid entry data.
File or DB that needs to be opened cannot be found.
A network connection has been lost in the middle of communications or the VM has run out of memory.
These exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
To make the program work smoother, the program should handle the exceptions properly with logic.

What's the proper term for run-time errors?

I know when you make a typo in your code, it's called a syntax error. but what do you call errors like using an element out of array bounds?
They're called runtime errors.
The other alternative term is, of course, bugs. I would say that runtime errors includes environmental problems such as network failure and disk corruption, whereas bugs are problems in the code itself.
I think the term you're looking for is Logic error.
Unlike a program with a syntax error, a program with a logic error is a valid program in the language, though it does not behave as intended.The only clue to the existence of logic errors is the production of wrong solutions.
Most introductory programming texts I've read divide programming errors into these two broad categories, syntax and logic errors.

The right time to handle all exceptions

I've done a few projects so far, and i've noticed that every single one i've written entirely without any exception handling, then at the end I do a lot of tests and handle them all.
is it right? i get thousands of exceptions while testing (which I fix right away) that if i've handled it i wouldn't see exactly where it is(when not using breakpoints or displaying it anywhere.. but it doesn't seem as practical) So I fix issues by checking any exceptions, then in the end I handle them anyway for any possible one that might have escaped (of course).
What about you? when do you guys take care of exceptions ?
Personally, I always define a global unhandled exception manager appropriate to the application type and have that log and email exceptions to my dev team. During QA, we'll then start to add specific exception management to routines that have predictable (and recoverable) issues. In every case possible, we add defensive programming code so that exceptions don't happen at all. (There's no need to trap an exception if you can test before you try code that could fail.)
My apps tend to end up with lots of defensive code (which should be built in from the start) and only some specific exception handling.
I prefer test-driven development. If there is an expected error condition, then test for it. If an unexpected error crops up, make a test for it, then fix it.
I would say that this is backwards (but common).
You might want to look into test driven development, and test first design
Hint: think of a behavior, write code to test for it, add it to your application.
I would definitely consider the exceptions thrown as you develop each interface and module.
That way you can test that they're reliably thrown (when you expect and not when you don't). Components consuming these components can then be written to be aware of these exceptions and handle (or not as they require).
It seems to me that you're ignoring some functionality of the components you're developing. I'll virtually always test for both correct functionality and the exceptional circumstances, to cover as many scenarios as I can as early as I can.
The answer to this one is a very clear "it depends".
You need to look at the specific situation; is an exception being thrown in a specific piece of code where it's possible to recover or handle the "exceptional" situation resulting in the exception being thrown? In that case, yes, catch the exception and deal with it at that level.
On the other hand, are you talking about non-recoverable errors? Then sure, catch them at a more global level, or possibly not at all (ie if there's nothing you can do about the exception, why are you catching it?)
The rule for where to catch exceptions usually is: wherever is the place you can meaningfully handle them.
Sometimes it depends upon the technology or target platform. I usually prefer an exception handling layer that takes care of all the exceptions. Each and every block of code is inside a try catch block.
Bottom line is that no exception should get caught by the OS or any other entity outside the program or code.
The beauty of exceptions compared to say returning error codes from API's is that you don't have to check for exceptions at every layer in your code. You can catch specific exceptions to determine specific error conditions and perhaps handle the error or rethrow a more appropriate exception. You also have to catch exceptions at a high level in your application to avoid unhandled exceptions.
One thing to note is that generally the user of the exception is the developer and not the end-user. The later normally doesn't appreciate the technical details of exceptions.
The most common thing I've seen is developers making a conscious choice as to what level to handle exceptions, and allow them to be thrown. Typically it will be at the level of a worker thread, or a high level of business logic. Allow the exceptions to happen, and have a blanket method of handling / logging them and protecting the user from them.
Timing is the only difference between what typically happens and what you do. Plan for it in your applications from the beginning, and do exception handling at high levels.
Fixing specific exceptions is done via your method of fix it when it's a problem. Sometimes a library I use will needlessly use exceptions to communicate information, and I will add specialized exception handling around all calls to that library. Often I will do this in a wrapper class that hides the implementation and exception handling from the rest of my application.

Are exceptions really for exceptional errors? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
It's my understanding that common wisdom says to only use exceptions for truly exceptional conditions (In fact, I've seen that statement here at SO several times).
However, Krzysztof Cwalina says:
One of the biggest misconceptions about exceptions is that they are for “exceptional conditions.” The reality is that they are for communicating error conditions. From a framework design perspective, there is no such thing as an “exceptional condition”. Whether a condition is exceptional or not depends on the context of usage, --- but reusable libraries rarely know how they will be used. For example, OutOfMemoryException might be exceptional for a simple data entry application; it’s not so exceptional for applications doing their own memory management (e.g. SQL server). In other words, one man’s exceptional condition is another man’s chronic condition.
He then also goes on to say that exceptions should be used for:
Usage errors
Program errors
System failures
Considering Krzysztof Cwalina is the PM for the CLR team at MS I ask: What do you think of his statement?
This sounds over-simplistic, but I think it makes sense to simply use exceptions where they are appropriate. In languages like Java and Python, exceptions are very common, especially in certain situations. Exceptions are appropriate for the type of error you want to bubble up through a code path and force the developer to explicitly catch. In my own coding, I consider the right time to add an exception when the error either can't be ignored, or it's simply more elegant to throw an exception instead of returning an error value to a function call etc.
Some of the most appropriate places for exceptions that I can think of offhand:
NotImplementedException - very appropriate way of designating that a particular
method or function isn't available, rather than simply returning without doing
anything.
OutOfMemory exceptions - it's difficult to imagine a better way of handling this
type of error, since it represents a process-wide or OS-wide memory allocation
failure. This is essential to deal with, of course!
NullPointerException - Accessing a null variable is a programmer mistake, and IMO
this is another good place to force an error to bubble to the surface
ArrayIndexException - In an unforgiving language like C, buffer overflows
are disastrous. Nicer languages might return a null value of some type, or in
some implementations, even wrap around the array. In my opinion, throwing an
exception is a much more elegant response.
This is by no means a comprehensive list, but hopefully it illustrates the point. Use exceptions where they are elegant and logical. As always with programming, the right tool for the right job is good advice. There's no point going exception-crazy for nothing, but it's equally unwise to completely ignore a powerful and elegant tool at your disposal.
For people who write frameworks, perhaps it's interesting.
For the rest of us, it's confusing (and possibly useless.) For ordinary applications, exceptions have to be set aside as "exceptional" situations. Exceptions interrupt the ordinary sequential presentation of your program.
You should be circumspect about breaking the ordinary top-to-bottom sequential processing of your program. The exception handling is -- intentionally -- hard to read. Therefore, reserve exceptions for things that are outside the standard scenarios.
Example: Don't use exceptions to validate user input. People make input mistakes all the time. That's not exceptional, that's why we write software. That's what if-statements are for.
When your application gets an OutOfMemory exception, there's no point in catching it. That's exceptional. The "sequential execution" assumption is out the window. Your application is doomed, just crash and hope that your RDBMS transaction finishes before you crash.
It is indeed difficult to know what exactly construes an "exceptional condition" which warrants the use of an exception in a program.
One instance that is very helpful for using communicating the cause of errors. As the quote from Krzysztof Cwalina mentions:
One of the biggest misconceptions
about exceptions is that they are for
“exceptional conditions.” The reality
is that they are for communicating
error conditions.
To give a concrete example, say we have a getHeader(File f) method that is reading some header from a file and returns a FileHeader object.
There can be several problems which can arise from trying to read data from a disk. Perhaps the file specified doesn't exist, file contains data that can't be read, unexpected disk access errors, running out of memory, etc. Having multiple means of failure means that there should be multiple ways to report what went wrong.
If exceptions weren't used, but there was a need to communicate the kind of error that occurred, with the current method signature, the best we can do is to return a null. Since getting a null isn't very informative, the best communication we get from that result is that "some kind of error happened, so we couldn't continue, sorry." -- It doesn't communicate the cause of the error.
(Or alternatively, we may have class constants for FileHeader objects which indicate FileNotFound conditions and such, emulating error codes, but that really reeks of having a boolean type with TRUE, FALSE, FILE_NOT_FOUND.)
If we had gotten a FileNotFound or DeviceNotReady exception (hypothetical), at least we know what the source of the error was, and if this was an end user application, we could handle the error in ways to solve the problem.
Using the exception mechanism gives a means of communication that doesn't require a fallback to using error codes for notification of conditions that aren't within the normal flow of execution.
However, that doesn't mean that everything should be handled by exceptions. As pointed out by S.Lott:
Don't use exceptions to validate user
input, for example. People make
mistakes all the time. That's what
if-statements are for.
That's one thing that can't be stressed enough. One of the dangers of not knowing when exactly to use exceptions is the tendency to go exception-happy; using exceptions where input validation would suffice.
There's really no point in defining and throwing a InvalidUserInput exception when all that is required to deal in such a situation is to notify the user of what is expected as input.
Also, it should be noted that user input is expected to have faulty input at some point. It's a defensive measure to validate input before handing off input from the outside world to the internals of the program.
It's a little bit difficult to decide what is exceptional and what is not.
Since I usually program in Python, and in that language exceptions are everywhere, to me an exception may represent anything from a system error to a completely legitimate condition.
For example, the "pythonic" way to check if a string contains an integer is to try int(theString) and see if it raises an exception. Is that an "exceptional error"?
Again, in Python the for loop is always thought of as acting on an iterator, and an iterator must raise a 'StopIteration' exception when it finishes its job (the for loop catches that exception). Is that "exceptional" by any means?
I think the closer to the ground are you are the less appropriate exceptions as a means of error communication become. At a higher abstraction such as in Java or .net, an exception may make for an elegant way to pass error messages to your callers. This however is not the case in C. This is also a framework vs api design decision.
If you practice "tell, don't ask" then an exception is just the way a program says "I can't do that". It is "exceptional" in that you say "do X" and it cannot do X. A simple error-handling situation. In some languages it is quite common to work this way, in Java and C++ people have other opinions because exceptions become quite costly.
General: exception just means "I can't"
Pragmatic: ... if you can afford to work that way in your language.
Citizenship: ... and your team allows it.
Here is the definition for exception: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Therefore, to answer your question, no. Exceptions are for disruptive events, which may or may not be exceptional. I love this definition, it's simple and works every time - if you buy into exceptions like I do. E.g., a user submits an incorrect un/pw, or you have an illegal argument/bad user input. Throwing an exception here is the most straightforward way of solving these problems, which are disruptive, but not exceptional, nor even unanticipated.
They probably should have been called disruptions, but that boat has sailed.
I think there are a couple of good reasons why exceptions should be used to catch unexpected problems.
Firstly, they create an object to encapsulate the exception, which by definition must make it a lot more expensive than processing a simple if-statement. As a Java example, you should call File.exists() rather than routinely expecting and handling a FileNotFoundException.
Secondly, exceptions that are caught outside the current method (or maybe even class) make the code much harder to read than if the handling is all there in in the one method.
Having said that, I personally love exceptions. They relieve you of the need of explicitly handling all of those may-happen-but-probably-never-will type errors, which cause you to repetitively write print-an-error-and-abort-on-non-zero-return-code handling of every method call.
My bottom line is... if you can reasonably expect it to happen then it's part of your application and you should code for it. Anything else is an exception.
I've been wondering about this myself. What do we mean by "exceptional"? Maybe there's no strict definition, but are there any rules of thumb that we can use to decide what's exceptional, in a given context?
For example, would it be fair to say that an "exceptional" condition is one that violates the contract of a function?
KCwalina has a point.
It will be good to identify cases where the code will fail (upto a limit)
I agree with S.Lott that sometimes validating is better than to throw Exception.
Having said that, OutOfMemory is not what you might expect in your application (unless it is allocating a large memory & needs memory to go ahead).
I think, it depends on the domain of the application.
The statement from Krzysztof Cwalina is a little misleading. The original statement refers 'exceptional conditions', for me it is natural that I am the one who defines what's exceptional or not. Nevertheless, I think the message passed through OK, since I think we are all talking about 'developer' exceptions.
Exceptions are great for communication, but with a little hierarchy design they are also great for some separation of concerns, specially between layers (DAO, Business, etc). Of course, this is only useful if you treat these exceptions differently.
A nice example of hierarchy is spring's data access exception hierarchy.
I think he is right. Take a look at number parsing in java. You cant even check input string before parsing. You are forced to parse and retrieve NFE if something went wrong. Is parse failure something exceptional? I think no.
I certainly believe exceptions should be used only if you have an exceptional condition.
The trouble is in the definition of "exceptional". Here is mine:
A condition is exceptional if it is outside the assumed normal
behaviour of the part of the system that raises the exception.
This has some implications:
Exceptional depends on your assumptions. If a function assumes that it is passed valid parameters, then throwing an IllegalArgumentException is OK. However if a function's contract says that it will correct input errors in input in some way, then this usage is "normal" and it shouldn't throw an exception on an input error.
Exceptional depends on sub-system layering. A network IO function could certainly raise an exception if the network is discommented, as it assumes a valid connection. A ESB-based message broker however would be expected to handle dropped connections, so if it used such a network IO function internally then it would need to catch and handle the error appropriately. In case it isn't obvious, try/catch is effectively equivalent to a subsystem saying "a condition which is exceptional for one of my components is actually considered normal by me, so I need to handle it".
The saying that exceptions should be used for exceptional circumstances is used in "Effective Java Second Edition": one of the best java books.
The trouble is that this is taken out of context. When the author states that exceptions should be exceptional, he had just shown an example of using exceptions to terminate a while loop - a bad exception use. To quote:
exceptions are, as their name implies, to
be used only for exceptional conditions; they should never be used for ordinary
control flow.
So it all depends on your definition of "exception condition". Taken out of context you can imply that it should very rarely be used.
Using exceptions in place of returning error codes is good, while using them in order to implement a "clever" or "faster" technique is not good. That's usually what is meant by "exceptional condition".
Checked exception - minor errors that aren't bugs and shouldn't halt execution. ex. IO or file parsing
Unchecked exception - programming "bug" that disobeys a method contract - ex. OutOfBoundsException. OR a error that makes continuing of execution a very bad idea - ex IO or file parsing of a very important file. Perhaps a config file.
What it comes down to is what tool is needed to do the job.
Exceptions are a very powerful tool. Before using them ask if you need this power and the complexity that comes with it.
Exceptions may appear simple, because you know that when the line with the exception is hit everything comes to a halt. What happens from here though?
Will an uncaught exception occur?
Will the exception be caught by global error handling?
Will the exception be handled by more nested and detailed error handling?
You have to know everything up the stack to know what that exception will do. This violates the concept of independence. That method now is dependent on error handling to do what you expect it to.
If I have a method I shouldn't care what is outside of that method. I should only care what the input is, how to process it, and how to return the response.
When you use an exception you are essentially saying, I don't care what happens from here, something went wrong and I don't want it getting any worse, do whatever needs to be done to mitigate the issue.
Now if you care about how to handle the error, you will do some more thinking and build that into the interface of the method e.g. if you are attempting to find some object possibly return the default of that object if one can't be found rather than throwing some exception like "Object not found".
When you build error handling into your methods interface, not only is that method's signature more descriptive of what it can do, but it places the responsibility of how to handle the error on the caller of the method. The caller method may be able to work through it or not, and it would report again up the chain if not. Eventually you will reach the application's entry point. Now it would be appropriate to throw an exception, since you better have a good understanding of how exceptions will be handled if you're working with the applications public interface.
Let me give you an example of my error handling for a web service.
Level 1. Global error handling in global.asax - That's the safety net to prevent uncaught exceptions. This should never intentionally be reached.
Level 2. Web service method - Wrapped in a try/catch to guarantee it will always comply with its json interface.
Level 3. Worker methods - These get data, process it, and return it raw to the web service method.
In the worker methods it's not right to throw an exception. Yes I have nested web service method error handling, but that method can be used in other places where this may not exist.
Instead if a worker method is used to get a record and the record can't be found, it just returns null. The web service method checks the response and when it finds null it knows it can't continue. The web service method knows it has error handling to return json so throwing an exception will just return the details in json of what happened. From a client's perspective it's great that it got packaged into json that can be easily parsed.
You see each piece just knows what it needs to do and does it. When you throw an exception in the mix you hijack the applications flow. Not only does this lead to hard to follow code, but the response to abusing exceptions is the try/catch. Now you are more likely to abuse another very powerful tool.
All too often I see a try/catch catching everything in the middle of an a application, because the developer got scared a method they use is more complex than it appears.