Saya baru saja melihat pertanyaan tentang coba-tangkap , yang dikatakan orang (termasuk Jon Skeet) blok tangkap kosong adalah ide yang sangat buruk? Kenapa ini? Apakah tidak ada situasi di mana tangkapan kosong bukan keputusan desain yang salah?
Maksud saya, misalnya, kadang-kadang Anda ingin mendapatkan beberapa info tambahan dari suatu tempat (layanan web, basis data) dan Anda benar-benar tidak peduli apakah Anda akan mendapatkan info ini atau tidak. Jadi Anda mencoba untuk mendapatkannya, dan jika sesuatu terjadi, tidak apa-apa, saya hanya akan menambahkan "tangkapan (Pengecualian diabaikan) {}" dan itu saja
exception-handling
try-catch
Samuel Carrijo
sumber
sumber
Jawaban:
Biasanya try-catch kosong adalah ide yang buruk karena Anda diam-diam menelan kondisi kesalahan dan kemudian melanjutkan eksekusi. Kadang-kadang ini mungkin hal yang benar untuk dilakukan, tetapi seringkali itu merupakan pertanda bahwa pengembang melihat pengecualian, tidak tahu harus berbuat apa, dan menggunakan tangkapan kosong untuk membungkam masalah.
Ini sama dengan pemrograman menempatkan pita hitam di atas lampu peringatan mesin.
Saya percaya bahwa cara Anda menangani pengecualian tergantung pada lapisan perangkat lunak yang Anda gunakan: Pengecualian di Hutan Hujan .
sumber
Mereka adalah ide yang buruk secara umum karena ini adalah kondisi yang benar-benar langka di mana kegagalan (kondisi luar biasa, lebih umum) bertemu dengan benar tanpa respons sama sekali. Selain itu,
catch
blok kosong adalah alat yang umum digunakan oleh orang yang menggunakan mesin pengecualian untuk memeriksa kesalahan yang seharusnya mereka lakukan terlebih dahulu.Mengatakan bahwa itu selalu buruk itu tidak benar ... itu benar sangat sedikit. Mungkin ada keadaan di mana Anda tidak peduli bahwa ada kesalahan atau bahwa keberadaan kesalahan entah bagaimana menunjukkan bahwa Anda tetap tidak bisa berbuat apa-apa (misalnya, ketika menulis kesalahan sebelumnya ke file log teks dan Anda mendapatkan
IOException
, artinya Anda tidak dapat menulis kesalahan baru).sumber
Saya tidak akan merentangkan hal-hal sejauh mengatakan bahwa siapa yang menggunakan blok tangkap kosong adalah programmer yang buruk dan tidak tahu apa yang dia lakukan ...
Saya menggunakan blok tangkap kosong jika perlu. Terkadang programmer perpustakaan yang saya konsumsi tidak tahu apa yang dia lakukan dan melempar pengecualian bahkan dalam situasi ketika tidak ada yang membutuhkannya.
Sebagai contoh, pertimbangkan beberapa perpustakaan http server, saya tidak peduli jika server melempar pengecualian karena klien telah terputus dan
index.html
tidak dapat dikirim.sumber
Ada beberapa contoh langka di mana hal itu dapat dibenarkan. Dengan Python Anda sering melihat konstruksi seperti ini:
Jadi mungkin OK (tergantung pada aplikasi Anda) untuk melakukan:
Dalam proyek .NET baru-baru ini, saya harus menulis kode untuk menghitung DLL plugin untuk menemukan kelas yang mengimplementasikan antarmuka tertentu. Bit kode yang relevan (dalam VB.NET, maaf) adalah:
Meskipun dalam kasus ini, saya akui bahwa mencatat kegagalan di suatu tempat mungkin akan menjadi peningkatan.
sumber
Blok tangkapan kosong biasanya dimasukkan karena pembuat kode tidak benar-benar tahu apa yang mereka lakukan. Di organisasi saya, blok tangkap kosong harus menyertakan komentar mengapa tidak melakukan apa pun dengan pengecualian adalah ide yang baik.
Pada catatan terkait, kebanyakan orang tidak tahu bahwa blok percobaan {} dapat diikuti dengan tangkapan {} atau akhirnya {}, hanya diperlukan satu.
sumber
Pengecualian hanya boleh dilemparkan jika benar-benar ada pengecualian - sesuatu terjadi di luar norma. Pada dasarnya blok tangkap kosong mengatakan "sesuatu yang buruk sedang terjadi, tapi aku tidak peduli". Ini ide yang buruk.
Jika Anda tidak ingin menangani pengecualian, biarkan merambat ke atas hingga mencapai beberapa kode yang bisa mengatasinya. Jika tidak ada yang dapat menangani pengecualian, itu harus menurunkan aplikasi.
sumber
catch (Exception) {}
itu ide yang buruk,catch (SpecificExceptionType) {}
mungkin baik-baik saja. Programmer DID memeriksa pengecualian, menggunakan tipe informasi dalam klausa tangkapan.I think it's okay if you catch a particular exception type of which you know it's only going to be raised for one particular reason, and you expect that exception and really don't need to do anything about it.
But even in that case, a debug message might be in order.
sumber
Per Josh Bloch - Item 65: Don't ignore Exceptions of Effective Java:
sumber
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's
On Error Resume Next
, except that anything in the try block after the exception is thrown will be skipped.Which doesn't help when something then breaks.
sumber
This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.
sumber
I think a completely empty catch block is a bad idea because there is no way to infer that ignoring the exception was the intended behavior of the code. It is not necessarily bad to swallow an exception and return false or null or some other value in some cases. The .net framework has many "try" methods that behave this way. As a rule of thumb if you swallow an exception, add a comment and a log statement if the application supports logging.
sumber
Because if an exception is thrown you won't ever see it - failing silently is the worst possible option - you'll get erroneous behavior and no idea to look where it's happening. At least put a log message there! Even if it's something that 'can never happen'!
sumber
Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up and being handled correctly by another try block. Always try and do something with the exception you are catching.
sumber
I find the most annoying with empty catch statements is when some other programmer did it. What I mean is when you need to debug code from somebody else any empty catch statements makes such an undertaking more difficult then it need to be. IMHO catch statements should always show some kind of error message - even if the error is not handled it should at least detect it (alt. on only in debug mode)
sumber
It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.
sumber
Generally, you should only catch the exceptions you can actually handle. That means be as specific as possible when catching exceptions. Catching all exceptions is rarely a good idea and ignoring all exceptions is almost always a very bad idea.
I can only think of a few instances where an empty catch block has some meaningful purpose. If whatever specific exception, you are catching is "handled" by just reattempting the action there would be no need to do anything in the catch block. However, it would still be a good idea to log the fact that the exception occurred.
Another example: CLR 2.0 changed the way unhandled exceptions on the finalizer thread are treated. Prior to 2.0 the process was allowed to survive this scenario. In the current CLR the process is terminated in case of an unhandled exception on the finalizer thread.
Keep in mind that you should only implement a finalizer if you really need one and even then you should do a little as possible in the finalizer. But if whatever work your finalizer must do could throw an exception, you need to pick between the lesser of two evils. Do you want to shut down the application due to the unhandled exception? Or do you want to proceed in a more or less undefined state? At least in theory the latter may be the lesser of two evils in some cases. In those case the empty catch block would prevent the process from being terminated.
sumber
So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only
EInfoFromIrrelevantSourceNotAvailable
and ignoring it, that would be fine, but you're not. You're also ignoringENetworkIsDown
, which may or may not be important. You're ignoringENetworkCardHasMelted
andEFPUHasDecidedThatOnePlusOneIsSeventeen
, which are almost certainly important.An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.
sumber
There are situations where you might use them, but they should be very infrequent. Situations where I might use one include:
exception logging; depending on context you might want an unhandled exception or message posted instead.
looping technical situations, like rendering or sound processing or a listbox callback, where the behaviour itself will demonstrate the problem, throwing an exception will just get in the way, and logging the exception will probably just result in 1000's of "failed to XXX" messages.
programs that cannot fail, although they should still at least be logging something.
for most winforms applications, I have found that it suffices to have a single try statement for every user input. I use the following methods: (AlertBox is just a quick MessageBox.Show wrapper)
Then every event handler can do something like:
or
Theoretically, you could have TryActionSilently, which might be better for rendering calls so that an exception doesn't generate an endless amount of messages.
sumber
If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.
sumber
You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.
sumber