try-catch exceptions in Swift [duplicate] - exception

This question already has answers here:
Error-Handling in Swift-Language
(13 answers)
Closed 8 years ago.
Is it possible to catch exceptions in Swift? Given the following code:
NSException.raise(NSRangeException,
format: "Now you've gone too far!",
arguments: CVaListPointer(fromUnsafePointer: UnsafePointer()))
Is it possible to prevent the exception from crashing the entire program? That is, what is the Swift equivalent of the following in Objective-C:
#try {
[NSException raise:NSRangeException format:#"Now you've gone too far!"];
}

It doesn't have exception handling, and this discussion in the developer forum discusses why it may be so:
but keep in mind that Cocoa and Cocoa Touch traditionally don't intend
for you to catch exceptions; they intend for you to not cause them to
be thrown in the first place. Ordinary errors should be handled with
optional types and inout NSError parameters; you should address any
situation that causes an assertion to fail (which seems to be the only
exception-throwing mechanism in Swift) by writing better code.

I believe that, as of today, Swift does not support this. It will most likely be added on future betas.

Related

Why does Swift make a distinction between designated and convenience initializer? [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 8 years ago.
Improve this question
Swift does make a distinction between designated and convenience initializers. The documentation, however, never states why this distinction is made.
From a programmer's point of view, it seems like an extra burden: I have to think whether some initialization mechanism is "designated" or "convenience" and there are even some practical inconveniences like that I cannot call a convenience constructor of the super class which might sometimes be totally appropriate. There have to be some advantages of this concept in return. Otherwise Apple would not have introduced this feature. So what is the reason for introducing this distinction in Swift? A references to an official statements would nice.
The distinction between designated initializers and convenience initializers is not new — it's been part of the Cocoa environment for a long time. The reason for this convention is to ensure that all the internal state managed by a class is configured as intended before a subclass, or code external to the class, starts trying to use it.
Explicit initialization is one of the "safety" features of Swift. Using values before they're initialized can lead to undefined behavior (read: bugs) in C. If you declare a variable in Swift, it has to have a value. (Optionals let you fudge this a bit while still being explicit about it.) Making Cocoa's initializer chaining convention into a requirement is how Swift ensures initialization safety on top of class inheritance.
But don't take my word for it. < /LeVar> There's a great explanation of this in the series of Swift talks from WWDC — check the videos.
Totally agree on the practical inconvenience, not being able to call a convenience constructor of the super class is a total PITA...
Though I don't have any "official" answer, the conclusion I've reached is that calling a designated constructor is the only future proof way to do so.
Convenience constructors always have the possibility of being changed in future API-releases, so making the initialization of your class depend on one is highly unsafe, while the designated initializer is always going to work, no matter what changes the API is going to go through along the way...

Learning Exception Handling Patterns [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
One thing that has always mystified me in programming is the use of appropriate exception handling. Code Complete points out that often times 90% of code is focused on handling exceptions. While I know the basics of implementing a basic exception, I have not found good general resources for such an important topic.
I am looking for good resources (not necessarily tied to a specific language) for learning how to implement good Exception Handling techniques. Most of the Exception Handling topics on stackoverflow seem to focus on a specific situation in a specific language. What would be your recommendations?
I have been a designer and coder of safety-critical systems for many years, and key to that type of system is robustness, one aspect of which is exception handling.
Some basic best practices:
1) At any level, catch only those exceptions you can deal with then and there. To "deal with" almost always means to retry or give up what you were trying to do, and that usually means that you should catch the exception one level up from where the exception-throwing call is issued.
2) Catch exactly those exceptions listed by the API documentation, no more, no less. Even if there are five exceptions listed for a call, don't catch their common base class (if they have one). However, you don't always need to catch all exceptions from the same call in the same place.
3) Don't pass nitty-gritty exceptions up to a level where they carry no meaningful information. Instead, catch the exception at the low level, log it if appropriate and return a status code or throw a more generic exception to the caller above.
4) Only use (and do use) catch-all handlers when you are in a critical section. Catch the exception, relinquish the resource (semaphore or whatever), rethrow the exception.
5) Logging an exception is not handling it. If all you do in a particular handler is log the exception, you should probably get rid of that handler.
6) Be very careful with exception handlers in loops, especially loops without a delay or a way out if the exception is thrown. You can easily get stuck in a busy loop that way.
I know of two good resources for proper exception handling strategies, they however pertain more to the .NET framework..
The first is the framework design guidelines by Krzysztof Cwalina (The lead designer of the .NET framework)
http://blogs.msdn.com/b/kcwalina/archive/2005/03/16/396787.aspx
The second is about what happens under the hood when exceptions are thrown, it will provide some good insight to help with your decision on how to handle exception. The book is called C# via CLR by Jeffrey Richter
http://shop.oreilly.com/product/9780735627048.do
Hope this helps.

Exception handling in Google Go language [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 last month.
Improve this question
I am wondering... I have read about Go some time ago and I tried to program something in it. I seems quite interesting. But I have reached handling "exceptions" in this language. I have read about their approach and it seems reasonable. I would like to know what are the advantages of the standard exceptional approach over the Go's style? What are the pros and cons?
Edit To be straight: I do not want to make any holy war about exceptions. I just wonder if this style of handling errors has any advantages? What are actual advantages of this style over standard exceptions? Is it worth wondering at all?
panic/recover is moral equivalent of try/catch exceptions. There is superficial difference (syntax) and a subtle, but important, difference of intended use.
The best explanations of problems with exceptions in general is "Cleaner, more elegant, wrong" and that's a good overview of pros/cons of exceptions vs. returning error codes.
Go designers decided that error handling by returning error codes from functions is the idiomatic Go way and the language supports multiple return values to make it syntactically easy. While panic/recover is provided, the difference is not of functionality but intended use.
Other languages exposing exceptions promote their use and in practice they are used frequently (sometimes even misused).
Go discourages the use of panic/recover. You can do it but you're only supposed to do it in very limited scenarios.
If you look at Go's own standard library, most uses of panic are for signaling fatal errors, indicating either an internal error (i.e. bug) in the library code or calling the library with wrong data (e.g. passing non-json data to json decoding functions).
But as the article you linked to points out: "The convention in the Go libraries is that even when a package uses panic internally, its external API still presents explicit error return values."
This is different from languages like C#, Java, Python or C++, where a lot of standard library code can throw exceptions to signal errors. Those languages want you to use exceptions. Go discourages the use of panic/recover.
To summarize:
idiomatic Go style is to use error codes to tell the caller about errors
use panic/recover only in rare cases:
to "crash" your program when encountering internal inconsistency indicating bugs in your code. It's basically a debugging aid.
if it dramatically simplifies error handling in your code (but if the code is to be used by others, never expose such panics to callers)
In practice the important thing is to use language's idiomatic style. In Go that's returning error codes and avoiding panic/recover. In C# that's using exceptions to signal some of the errors.

Exception-handling antipatterns [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Exception handling is a challenge for new and experienced developers alike. What are some examples of exception handling antipatterns that people have seen?
Bad cleanup logic
Throwing in clean up code from a destructor. This one is doubly bad, because a.) throwing from a destructor is generally bad and b.) because even if you could catch it, there isn't anything to do about it.
File::~File()
{
if (!close(fd_)) {
throw FileIOException("Could not close descriptor.", fd_);
}
}
The UI from hell
try {
// ... lots of UI logic here ...
} catch (Exception error) {
alert("This program has performed an illegal operation and needs to quit.");
System.exit(-1);
}
Retrying without backoff
bool has_connected = false;
while (!has_connected) {
try {
EstablishConnection();
has_connected = true;
} catch (...) {
// IGNORE
}
}
Here's one that isn't entirely unlike things that I've seen before.
try {
methodThatThrowsSomeException1();
methodThatThrowsSomeOtherException2();
methodThatThrowsSomeOtherException3();
methodThatThrowsSomeOtherException4();
methodThatThrowsSomeOtherException5();
methodThatThrowsSomeOtherException6();
...
methodThatThrowsYetAnotherException20();
} catch (Throwable e) {
log.error("There was a problem reading the user role");
role = PRIVILEGED;
}
catch (...) in C++.
Probably the worst way to make your code look stable...
The same applies to any other language, where you catch exceptions you don't expect, and just swallow them silently in order to hide the error from the user. But the (...) is usually used to catch exceptions such as NULL pointer dereference or access denials, which means the error swallowed will probably manifest itself later in ways that might look totaly unrelated to the root of the problem.
My biggest pet peeve is setting up an exception inheritance hierarchy in which descendant relationships provide little bearing upon whether an exception should be caught or not. There's not much do be done about pre-defined exceptions, but my preference is to avoid throwing those and instead define new exceptions for cases where the caller should assume that the system state is fine except to the extent implied by the fact that the routine didn't return successfully, versus those where the system state is trashed. For example, if a method is supposed to open a file and return a new document object, but there's some problem parsing the file, it shouldn't kill the whole application. It should let the user know the file couldn't be opened, and then proceed as though the user hadn't tried to open the file. It's irrelevant why the file didn't open; the question is whether application state has been corrupted. Unfortunately, none of the standard exceptions are very good at dealing with that.
Using exceptions in shared libraries that are meant to be used from multiple languages / C++ dialects. Since there's no way the C++ compiler can guarantee you aren't accidentally throwing an exception back to the caller (unlike in Java) you're just setting yourself up for a crash.

When to use custom exceptions vs. existing exceptions vs. generic exceptions [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 1 year ago.
Improve this question
I'm trying to figure out what the correct form of exceptions to throw would be for a library I am writing. One example of what I need to handle is logging a user in to a station. They do this by scanning a badge. Possible things that could go wrong include:
Their badge is deactivated
They don't have permission to work at this station
The badge scanned does not exist in the system
They are already logged in to another station elsewhere
The database is down
Internal DB error (happens sometimes if the badge didn't get set up correctly)
An application using this library will have to handle these exceptions one way or another. It's possible they may decide to just say "Error" or they may want to give the user more useful information. What's the best practice in this situation? Create a custom exception for each possibility? Use existing exceptions? Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)? I'm thinking it's some sort of mix of the first two, using existing exceptions where applicable, and creating new ones where needed (and grouping exceptions where it makes sense).
I essentially agree with your current thinking.
Use existing core exceptions where appropriate: ArgumentException, InvalidOperationException, etc. Don't try to repurpose exceptions that are specific to some other module. Use those exceptions that have a clear, generic purpose, and don't use them for business rules. For example, InvalidOperationException should indicate a bad operation w/ regards to your API, not a violation of a business rule.
For exceptions specific to your library, create a base exception class, BadgeAuthException, and always throw that. The specific scenarios should each get their own subclass (BadgeDeactivatedException, NoPermissionsAtWorkstationException, etc.) This way apps can handle the individual sub-cases separately if they want to, but they can also just catch the generic BadgeAuthException if they don't want to grovel in specifics.
Whatever you do, ensure that the Message field always contains useful information beyond just the exception name.
Use Exception and pass in the reason (throw new Exception("Badge is deactivated.");)
This certainly is a bad practice, because it violates the purpose of exceptions - not just to signal an abnormal situation, but provide an ability to distinguish exceptions on a type level, so the user of a module can make a decision depending on a type of exception.
Generally, it is good to reuse standard exceptions as far as they can fully describe abnormal situations your code actually faces. It is quite hard to give an advise in a current situation, because exceptions can often depend on semantics ( argument exception or invalid operation exception (maybe suitable for 'Their badge is deactivated' case, for example ).
You have two species of exceptions.
Those that are specific to your application, where it's good to avoid any existing exceptions.
Your application-specific exceptions should simplify the use cases for the folks who use your libraries. 3 of your application specific exceptions are things users can do. The fourth (badge does not exist) is clearly not procedural, but far more serious.
It looks like you have two application-specific errors: user-oriented things and administrative mistakes.
The others are part of some other piece of technology; i.e., database errors. You can -- generally -- ignore these. If the DB isn't available, the API will throw errors and you can let those bubble up through your library.
You can also "wrap" these as an application-specific exception which contains a lower-level exception. This is sometimes helpful if there is a lot of lower-level technology. In your case, it's just a database. Ignore it and let the DB errors bubble through.
You can nearly never go wrong by having fine-grained exception classes that extend a common base class. That way, callers who need to specifically catch some and let others through can, and callers who want to treat them all together can do so.
I think you need to have one base exception and one subtype exception for each of the situalitions you describe (actually you can make db down and internal db error to have the same base exception). The key point is that it is good practice to have your own exceptions for your library.