Java Java Data Structures Efficiency! Design the UI

Andre Kucharzyk
Andre Kucharzyk
4,478 Points

Why we had to import an exception in this exercise?

Why we had to import an exception: import java.io.IOException ? It's the first time we had to do it in this course and I'm not sure why?

3 Answers

Ryan Sherry
Ryan Sherry
12,447 Points

Hi Andre,

I'm definitely not an expert but I'll do my best to answer your question.

From what I have gathered so far, there are certain bits of code that require exception handling incase something goes wrong (i.e. InputStreams are Input/Output and could result in an I/O exception).

The exception must be handled (either a try/catch or by throwing) using the IOException class. The IOException class must be imported because it is not included in the standard java packages.

The good news is, if we were using an IDE (i.e. Android Studio or InteliJ), it will actually highlight your code with red lines and with a couple clicks, the try/catch block (or throws) as well as the import will automatically be generated for you.

Hope that helps!

Hello Ryan :) Do you know the answer, why is it a good (or necessary?) prectice to make this bubbling with exceptions? Why isn't a good way to handle that exception there in that method where we get the user input?

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Student 15,032 Points

Hi Andre Kucharzyk

Classes from package java.lang. do not need to imported for example String , Object Classes which are from java.lang package. The java.lang package is implicitly imported by every one of Java source file so no need to import.

However, you need to explicitly import Exception Classes contained in other Java packages like the exceptions inside the Java io package e.g. FileNotFoundException, IOException, InterruptedIOException.

Also note that Java defines several exception classes inside the standard package java.lang and you don't need to import these Exceptions. Topping this list would be the notorious NullPointerException, ArithmeticException, IllegalStateException, IndexOutOfBoundsException etc. I think these are the exceptions we h ave encountered in this course without the need of importing them.

Cheers

Tonnie Fanadez
Tonnie Fanadez
UX Design Techdegree Student 15,032 Points

What's up Gal Krisztina

Hope the late query counts.

Catching and Handling the Exception should be done when inside method that knows what to do and take appropriate course of action to handle the error. If the method cannot take take the appropriate action then it should only concern itself to generate the exception and exception info and then throw it.