Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java exceptions rationale

A quite theoretical question this time. So I'm using this function in Eclipse:

CsvReader csv = new CsvReader("src/maindroite.csv");

Which can't run because "Unhandled exception type FileNotFoundException". Ok, I understand that I have to add something for the case where the file doesn't exist, at which point I usually add a few lines to catche the exception and throw it away. But my question is: why do I need to catch the exception even when the file do exist? And actually, why do I even have this Exception thing for some functions and not others?

For example, let's say I'm trying to run:

ImageIcon icon1 = new ImageIcon("src/square.jpg");
ImageIcon icon2 = new ImageIcon("src/circle.jpg");

Where "square.jpg" exists but not "circle.jpg". The program will create icon1, but not icon2, because it can't. But I don't need to add an ExceptionHandler for the case where the image doesn't exist. What is the difference between both functions?

To sum it up:

  • Why do I have to add an ExceptionHandler when the file do exist?
  • Why do I have to add an ExceptionHandler for some functions and not others?

Thanks!

like image 641
Cristol.GdM Avatar asked Feb 22 '23 22:02

Cristol.GdM


1 Answers

Why do I have to add an ExceptionHandler when the file do exist?

Basically you have to add it regardless, because you cannot write conditional code like that, in short there is no way that for the compiler to know before runtime if the file exists or not, therefore the compiler forces yo to put a try/catch block, since FileNotFoundException is a checked exception.

Why do I have to add an ExceptionHandler for some functions and not others?

You only have to add try/catch blocks to anything that throws a checked exception, that is anything that does **NOT* inherit from RuntimeException or Error classes. Subclasses of Error and RuntimeException are not checked exceptions and you may either put the try/catch or not the compiler does not care. Since the constructor for ImageIcon does not throw any kind of exceptions and will simply return null if the image does not exist there is no need to do a try/catch block.*

like image 123
Oscar Gomez Avatar answered Feb 24 '23 11:02

Oscar Gomez