Chapter 20 - Exceptions Handling Flashcards

1
Q

What is a Java Exception?

A

In Java, an exception is an event that occurs during the execution of a program and disrupts the normal flow of the application. Exceptions represent unexpected or erroneous conditions that can occur at runtime. These conditions can be caused by various factors, including user input, hardware failures, network issues, or logical errors in the code.

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

Types of Exceptions (checked unchecked)

A

Checked Exception:

It is an exception that occurs at compile time, also called compile time exceptions. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

Unchecked Exception:

It is an exception that occurs at the time of execution. These are also called Runtime Exceptions. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to specify or catch the exceptions.

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

Exception Handling Methods

A

try
catch
finally
throw
throws

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

The finally Block

A

In addition to try and catch blocks, Java also provides the finally block, which is used for cleanup code that should be executed regardless of whether an exception was thrown or not. This block is optional but can be handy for tasks like closing resources (e.g., files or database connections) or releasing acquired locks.

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

Exceptions Hierarchy

A

All exception and error types are subclasses of class Throwable, which is the base class of hierarchy. One branch is headed by Error which occurs at run-time and other by Exception that can happen either at compile time or run-time.

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

Difference between Exceptions and errors

A

Exceptions:

Exceptions represent exceptional conditions that occur during the execution of a program. These conditions are typically caused by errors in the program logic, unexpected inputs, or external factors beyond the program’s control.
Exceptions are further divided into two categories: checked exceptions and unchecked exceptions.
Checked exceptions must be either caught by the code or declared in the method’s signature using the throws keyword. Examples include IOException, SQLException, etc.
Unchecked exceptions (also known as runtime exceptions) do not need to be caught or declared. They typically indicate programming errors or unexpected conditions that could have been avoided with proper coding practices. Examples include NullPointerException, ArrayIndexOutOfBoundsException, etc.
Exceptions are meant to be caught and handled by the application to prevent abnormal termination and provide error recovery mechanisms.

Errors:

Errors, on the other hand, represent serious problems that are generally beyond the control of the application. They indicate situations that are abnormal and not recoverable by the application itself.
Errors are typically caused by issues at the system level, such as running out of memory (OutOfMemoryError), stack overflow (StackOverflowError), hardware failures, or JVM internal errors.
Unlike exceptions, errors are not meant to be caught or handled by the application. They signal severe problems that often require intervention at the system level or by the administrator.
Attempting to catch or handle errors is generally discouraged because the application may not be in a stable state to continue execution.

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

List User defined Exc and Built-in exc also errors

A

User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, a user can also create exceptions which are called ‘User-Defined Exceptions’.

Built in Exceptions:
(Checked compile time)
IOException - Input/Output
SQLException
ClassNotFoundException
InterruptedException

(Uncheced Runtime)

NullPointerException
ArrayIndexOutOfBoundsException
NumberFormatException
IllegalArgumentException
IllegalStateException
ClassCastException

Errors:
OutOfMemoryError
StackOverflowError
InternalError
NoClassDefFoundError

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

difference between final vs finally vs finalize

A

final:
final is a keyword in Java used to declare constants, methods, and classes.
When applied to a variable, it indicates that the variable’s value cannot be changed once initialized.
When applied to a method, it indicates that the method cannot be overridden by subclasses.
When applied to a class, it indicates that the class cannot be subclassed.

finally:
finally is a block in Java used in exception handling to execute a block of code regardless of whether an exception is thrown or not.
It is typically used along with try and catch blocks to ensure that certain cleanup or resource releasing tasks are performed, such as closing streams or releasing locks.
finally block always executes, even if an exception occurs in the try block or a matching catch block is found.

finalize:
finalize is a method in Java defined in the Object class.
It is called by the garbage collector before reclaiming the memory occupied by an object that is eligible for garbage collection.
The finalize method can be overridden in a class to define specific cleanup or resource releasing tasks to be performed before the object is garbage collected.
However, it’s important to note that the use of finalize method for resource cleanup is generally discouraged due to unpredictable timing of garbage collection and the potential for resource leaks.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. How Exception Handling Works in Java
A

Step 1: When an error occurs within a method, the method creates an object and hands it off to the runtime system this object is called an exception object. The exception object contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Step 2: After a method throws an exception, the runtime system attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. The following diagram shows the call stack of three method calls, where the first method called has the exception handler.

Step 3: The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler. The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.

Step 4: The exception handler chosen is said to catch the exception. If the runtime system exhaustively searches all the methods on the call stack without finding an appropriate exception handler, as shown in the following diagram, the runtime system (and, consequently, the program) terminates.

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

What is the purpose of the throw and throws keywords?

A

throw: The throw keyword is used to explicitly throw an exception within a method or block of code. It’s typically followed by an instance of a subclass of Throwable (usually an instance of Exception or one of its subclasses). When an exception is thrown using throw, it interrupts the normal flow of the program and transfers control to the nearest enclosing try block’s catch clause, or if there’s no matching catch clause, it propagates up the call stack.Example:

throws: The throws keyword is used in a method signature to declare the types of exceptions that the method might throw, but doesn’t handle itself. It indicates that the method can potentially throw one or more exceptions of the specified types. When a method is declared with throws, it’s the responsibility of the caller to handle or propagate the exceptions.Example:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
  1. What is OutOfMemoryError in Java?
A

OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and it’s thrown by JVM when it ran out of heap memory.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. What is Chained Exceptions in Java?
A

Chained exceptions, introduced in Java 1.4, allow one exception to be nested within another. This feature is helpful when you want to provide additional context or information about the cause of an exception.

In Java, when an exception occurs, you can create a new exception object and pass the original exception (the cause) as an argument to the constructor of the new exception. This establishes a cause-and-effect relationship between the two exceptions, forming a chain.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
  1. What happens when an exception is thrown by the main method?
A

When an exception is thrown by main() method, Java Runtime terminates the program and print the exception message and stack trace in system console.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  1. What is a stacktrace and how does it relate to an exception?
A

A stack trace provides the names of the classes and methods that were called, from the start of the application to the point an exception occurred.
It’s a very useful debugging tool since it enables us to determine exactly where the exception was thrown in the application and the original causes that led to it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
  1. Can you throw any exception inside a lambda expression’s body?
A

When using a standard functional interface already provided by Java, you can only throw unchecked exceptions because standard functional interfaces do not have a “throws” clause in method signatures:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. What are the rules we need to follow when overriding a method that throws an exception?
A

When the parent class method doesn’t throw any exceptions, the child class method can’t throw any checked exception, but it may throw any unchecked.
When the parent class method throws one or more checked exceptions, the child class method can throw any unchecked exception; all, none or a subset of the declared checked exceptions, and even a greater number of these as long as they have the same scope or narrower.

When the parent class method has a throws clause with an unchecked exception, the child class method can throw none or any number of unchecked exceptions, even though they are not related.