Breaking down Exceptions in JAVA

Japneet Sachdeva
2 min readMar 25, 2024

--

What are exceptions in JAVA?

While executing our code, if it gets into some runtime errors which can stop or prevent it’s regular flow of execution, then we can use exception handling to preserve. There lot’s of exceptions such as IOException, SQLException, etc.

What are different types of exceptions?

In Java there are 2 types of Exceptions in Java

i. Compile Time also called as Checked Exception

Exception that are shown by Java before the execution of the code is

called as Compile Time Exception

Example: SQL Exception, IOException

ii. Run Time also called as Unchecked Exception

Exception that are shown by Java during the execution of the code is

called as Run Time Exception

Example: Null Pointer Exception, ArrayIndexOutBoundException

Exception Hierarchy?

Throwable: The base class for all exceptions and errors in Java.

Exception: Represents recoverable issues within the application’s control, like NullPointerException or FileNotFoundException.

Error: Indicates more severe, unexpected problems outside your control, like OutOfMemoryError or StackOverflowError.

Exception Handling Techniques?

Try-Catch-Finally: Blocks used to handle specific exceptions or provide cleanup logic regardless of exceptions.

Exception Chaining: Wrapping lower-level exceptions with higher-level ones for clearer context.

Custom Exceptions: Creating your own exception types to represent specific application errors.

Best Practices?

Avoid Over-Catch: Catching broad exceptions like Exceptions hides specific errors.

Log Exceptions: Use logging libraries to track and analyze exception occurrences.

Provide Informative Error Messages: Clearly explain the error to users and developers.

Test Exception Handling: Ensure your code handles expected exceptions gracefully.

What is the difference between throw and throws?

a. There are 2 ways using which exceptions can be handled

i. Throws

ii. Try catch

b. throw is a keyword in java which is used to throw an exception manually

Most Preferred approach of Handling exceptions is always via Try Catch.

Can I try with multiple catches possible?

Yes ,we can have a single try block with multiple catch blocks.

Can multiple try with a single catch be possible?

No, we cannot have multiple try block with a single catch block

-x-x-

Crack Test Automation Interviews using JAVA with lots of coding problems and solutions: https://topmate.io/japneet_sachdeva/799592

Subscribe my YouTube channel: https://www.youtube.com/@IamJapneetSachdeva

#japneetsachdeva

--

--

Japneet Sachdeva
Japneet Sachdeva

No responses yet