Is it a good idea to encase the entire code in a try/catch? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Is it a good idea to encase the entire code in a try/catch?

Im wondering for developments reasons

7th Aug 2018, 12:49 PM
Evan Martine
2 Answers
+ 2
generally it is better to use try in places an exception might occur so if you have a method that depends on importing a data file, you should put a try block where you use that method instead of placing it within the method definition, this allows you to catch and handle the exception elsewhere so you could specify your method throws and IOException. ex public void dataFile(File file) throws IOException{ file.open() } when you use the throws keyword no one will be able to call this method without placing it in a try block, you do this to ensure exceptions are handled and that you dont have to do it inside the method itself.
7th Aug 2018, 1:13 PM
Robert Atkins
Robert Atkins - avatar
+ 2
in my personal opinion, it's not... one should individually check each statement in try catch if possible (as it increases coding lines and time) sometimes you don't have to go for try catch for few line.. consider int* pArr = new [8];..... Here, you can check whether pArr is null or not to proceed further..
7th Aug 2018, 1:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar