Exception Handling in Java

image

Nobody likes exceptions, nevertheless we have to deal with them. The good thing is that Java provides a powerful mechanism for exception handling which is easy to understand and use. In Java, an exception can occur due to various different reasons such as invalid data entered by the user, loss of network connection in the middle of communication or JVM has run out of memory or a file needs to be opened but doesn’t exist.

There are two types of exceptions in java: Checked and Unchecked or also known as Compile time Exception and Runtime Exception respectively. The checked exceptions are those for which the compiler checks and forces you to decide whether you want to try, catch, finally or throw the exception, while unchecked exceptions are those for which the compiler doesn’t force you to decide its handling.

Now we’ll take a look at the above mentioned keywords that are used for exception handling in java

• Try-catch: Try block is used to enclose the code segment that might throw an exception. Catch block is used to handle the exception. There can be multiple catch blocks with a single try block.

• Finally: This is an optional block which can only be used with a try-catch block. Finally block gets executed after the try-catch block and is always executed irrespective of whether the exception occurred or not.

• Throw: The ‘throw’ keyword is used to explicitly throw an exception. This keyword is used for creating custom exceptions and handle them accordingly. It can be used to throw checked as well as unchecked exceptions.

• Throws: The ‘throws’ keyword is used to declare an exception. It provides the information to the programmer that there might be an exception therefore allowing the programmer to provide an exception handling code so that the program runs smoothly.

I wouldn’t go deeper into the details as it would require much more explaining and examples. You can find a good tutorial for exception handling on the internet which would provide an in-depth explanation of the topic.
Here I have provided few of the references which I found useful-
https://www.journaldev.com/1696/exception-handling-in-java
https://www.javatpoint.com/
https://stackify.com/specify-handle-exceptions-java/
https://www.geeksforgeeks.org/exceptions-in-java/

Comments (2)