Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I care about caught exceptions in Java?

I've noticed on several occasions that enabling exception breakpoints in Eclipse & Android Studio has the "Caught exceptions" box checked by default. Is there a reason I should leave this checked?

like image 304
Jeremy White Avatar asked Oct 30 '22 15:10

Jeremy White


1 Answers

Why should I care about caught exceptions in Java?

Exceptions help you when something in your code or logic breaks. Instead of using if and else statements to handle errors, which there is more code to write and the code itself might break in the process, you can use exceptions. Exceptions allow you to write the code as you usually do and to deal with them by adding try, catch and finally blocks. Then the program will use the exceptions to indicate that an error occurred.

  • try is the block of code that the exception can occur and it should contain at least one catch (or many), or finally block.
  • catch is the block of code that will handle a particular type of exception.
  • finally is the block of code that is guaranteed to execute after the try block.

"To throw an exception, use the throw statement and provide it with an exception object — a descendant of Throwable — to provide information about the specific error that occurred. A method that throws an uncaught, checked exception must include a throws clause in its declaration." - From Exception Oracle Documentation

Exceptions objects have more information about the error that it is thrown. "With the exception chaining, an exception can point to the exception that caused it, which can in turn point to the exception that caused it, and so on." - From Exception Oracle Documentation

I've noticed on several occasions that enabling exception breakpoints in Eclipse & Android Studio has the "Caught exceptions" box checked by default. Is there a reason I should leave this checked?

Caught exceptions checkbox is used if you want the execution to be suspended when the exception is thrown and catch it with the catch clause.

Android

Android exceptions are pretty much the same as java. However, in Android there is no console so you have to report the exceptions to the user. The way exceptions are shown to the user are in a toast or dialog.

You can get more information about exceptions here: https://docs.oracle.com/javase/tutorial/essential/exceptions/ http://www.javacodegeeks.com/2013/07/java-exception-handling-tutorial-with-examples-and-best-practices.html https://androidcookbook.com/Recipe.seam;jsessionid=ED0972E495383DBA84BE448E717BB749?recipeId=75&recipeFrom=ViewTOC

like image 94
Victor Luna Avatar answered Nov 10 '22 20:11

Victor Luna