Java Core: Exceptions Flashcards

1
Q

What are Exceptions in Java?

A

Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What’s the difference between checked and unchecked exceptions?

A

i. Checked exceptions are exceptions expected to be handled in compile-time by either using a try-catch statement or using throws keyword.
ii. Unchecked exceptions extend Error or RuntimeException classes, which JVM can throw during runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain the inheritance hierarchy of these exception classes - Exception, IOException, Throwable, Error, RuntimeException, NullPointerException.

A
  • Error (unchecked) is –> Throwable.
    - IOException (checked) is –> Exception (checked - is not RuntimeException) is –> Throwable.
  • NullPointerException (unchecked) is –> RuntimeException (unchecked) is –> Exception (checked - is runtime exception) is –> Throwable.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

When are Errors thrown? How should you handle them?

A

The ‘Error’ should be left unhandled since there is no way to recover from an Error.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Should you catch ‘Throwable’?

A

The Throwable includes and Error that should be left unhandled (it indicates an unrecoverable program and stops the execution flow).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Can you use a ‘try-finally’ construct without using the ‘catch’ block?

A

Yes, the ‘finally’ block is meant for code that has to be executed regardless of errors thrown or caught in try ‘block’, for example, closing a file or connection.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

When implementing your own custom exceptions, would you prefer checked or unchecked exceptions? Why?

A

(Unchecked) Usually, when designing your own exceptions, those are extensions of RuntimeExceptions, used to identify and pass along information on what exactly went wrong in the program’s logic - for example, missing mandatory information from an input, instead of a NullPointerException that has a broader meaning.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly