Когда портирование Java кодирует к ObjC, как лучше всего представить контролируемые исключительные ситуации?

Необходимо отправить данные по HTTP. Используйте класс WebRequest для регистрации данных. Необходимо будет отправить другие данные с запросом сообщения, чтобы гарантировать, чтобы у Вас был допустимый конверт SOAP. Читайте спецификация SOAP для всех деталей.

8
задан Quinn Taylor 13 July 2009 в 14:10
поделиться

6 ответов

You should definitely avoid exceptions for things like parsing numbers from strings. In Objective-C, exceptions represent programmer error, not user input error, or even unavailable files. (Part of the reason is that exception handling is always more costly and complex than more "conventional" error handling. Regardless of the fact that entering @try blocks is "zero cost" in 64-bit, it's still slow whenever an exception is actually raised.) Of course, you're allowed to use exceptions as you like, but it's not the Cocoa way, and you'll find yourself at odds with other Objective-C code. People who use your code will be incredibly annoyed that you throw exceptions in cases that should just result in an error.

From Apple's own docs:

"In many environments, use of exceptions is fairly commonplace. For example, you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors. Instead you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object."

Look at how built-in Cocoa classes handle errors like this. For example, NSString has methods like -floatValue that return 0 if it fails. A better solution for your particular situation might be how NSScanner does it, such as in -scanFloat: — accept a pointer to the field where the result should be stored, and return YES or NO based on whether the parse was successful.

Aside from Obejctive-C convention and best practices, NSError is much more robust and flexibly than NSException, and allows the caller to effectively ignore the problem if they want to. I suggest reading through the Error Handling Programming Guide For Cocoa. Note: If you accept an NSError** param, I strongly suggest you also design to allow the client to pass NULL if they don't want to receive any error information. Every Cocoa class I'm aware of does this for errors, including NSString.

Although the ported code may end up looking totally different from the Java code, recognize that it will be used by Objective-C code, not the same clients of the Java equivalent. Definitely match the idioms of the language. The port will not be a mirror image of the Java code, but it will be much more correct (for Objective-C) as a result.

16
ответ дан 5 December 2019 в 05:45
поделиться

В Какао исключения действительно должны использоваться только для «ошибок программирования»; философия заключается в том, чтобы позволить приложению уловить их, дать пользователю возможность сохранить то, что он делает, и выйти. Во-первых, не все фреймворки или пути кода могут быть на 100% безопасными для исключений, поэтому это может быть единственно безопасным способом действий. Для ошибок, которые можно предвидеть и исправить, следует использовать NSError, обычно через выходной параметр.

7
ответ дан 5 December 2019 в 05:45
поделиться

Вы правы, что «ошибки out обычно являются лучшим решением для ObjC». Очень редко вы найдете API в Какао, которое выдает исключение (если вы не выполнили предварительные условия для API, но в этом случае поведение по умолчанию не определено).

Если вы ожидаете, что этот код будет жить дальше вас и быть принятым другими разработчиками Cocoa, я бы рекомендовал использовать наши ошибки. Я работаю над кодом, созданным людьми, незнакомыми с Какао и широко использующими исключения, и над ними очень тяжело работать.

3
ответ дан 5 December 2019 в 05:45
поделиться

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

2
ответ дан 5 December 2019 в 05:45
поделиться

I'm a big fan of the out error approach that Objective-C uses. You HAVE to handle exceptions, but you can choose to ignore out errors if you want to. It all fits with the Objective-C attitude that "the programmer knows what they're doing." It also makes Objective-C a very clean-looking language, because your code isn't cluttered with try-catch blocks.

That said - you might want to consider: Are there any scenarios where exceptions are ignored? Are the exceptions you throw truly critical? Do you find yourself writing simple catch blocks that clean up variables and continue on? I'd lean toward out errors because I like the syntax and Objective-C reserves exceptions for only the most critical errors.

2
ответ дан 5 December 2019 в 05:45
поделиться

Исключения, вероятно, являются лучшим подходом, поскольку 64-битный Obj-C ABI (среда выполнения) использует исключения с нулевой стоимостью, поэтому вы получаете более чистый код без каких-либо реальных затрат. Конечно, в 32-битных версиях старые исключения setjmp / longjmp все еще используются, и они не взаимодействуют с C ++, так что если это цель, то у вас проблема.

-1
ответ дан 5 December 2019 в 05:45
поделиться