Exceptions are very important topic of java programming , In this article we will look about Exception in java
We will cover following things in Exception handling:
- What are exceptions?
- Need of exception handling?
- Hierarchy of exception?
- Difference between runtime and compile time exceptions?
- How try – catch-finally work?
Exceptions are basically unlikely event which disrupts the normal flow of execution of a Java program. Along with exceptions there are Errors which again are more severe failure reasons of the program like memory issues. Exceptions can be due to various reason like incorrect data entered by user, hardware failure, network connection failure, Database server down, incorrect file format, wrong input format and many more. Java categorizes all these exceptions into two major categories Runtime or unchecked exceptions and compile time or checked exceptions.
As you can see in the above diagram Throwable is the mother class for Exceptions and Errors. Exception class is further sub-classed into RuntimeException and Checked exception like IOExceptions etc.
So what is the difference between Errors and Exceptions:
Error
|
Exceptions
|
Error are always unchecked
|
Exception can be checked or unchecked
|
Errors are caused by the environment in which application is running like memory issues
|
Exception are mainly caused by application or because of programmer mistakes
|
Errors cant be handle because even if we catch them the program will not able to execute as the problem are mainly related with resource
|
Exceptions can be handled and will be able to make the problem successfully execute.
|
Now let us move ahead with what are the difference between checked and unchecked exceptions are how do they work in Java:
Checked exceptions are also known as compile time exceptions. Basically whenever we have a checked exception compiler tell us hey this block of code can throw exception and you should either handle it or declare it. Java provides many checked exceptions like IOException, SQLException etc that need to be handled by putting them inside a try catch block or can be declared using throws clause.
Read Also : how to create a new file in java
Read Also : how to create a new file in java
UncheckedException are runtime exceptions i.e the compiler does not prompt for its occurrence and is usually due to human errors like invalid arguments, calling method on null objects etc. They extend from the class RuntimeException and are not easy to find out.
Eg. NullPointerException, ArrayIndexOutOfBoundException, UncheckedException
Should be handled on code level rather than using try catch blocks as they have occurred due to unavoidable reasons.
Some ways to handle unchecked exceptions are:
• Always check for possible null values before calling methods or operations on them.
• Be careful while iterating over arrays or strings and check their lengths to avoid IndexOutOfBoundException.
• Use instanceof to check the object type to avoid ClassCastException
Some ways to handle checked exceptions are:
Checked exceptions need to be handled or declared. Let us see an example of handling with try catch block:
As we can see we are trying to read a file and the compiler prompts with and compile time error to either add throws or surround with try catch.
Using try catch block to handle compile time exception:
Java provides a mechanism of try-catch-finally blocks to handle the expected exceptions in the applications. We write the block of code which can possibly throw an error inside the try block or can intentionally throw an error from the try block using throw keyword and if at any point the application fails the catch block handles the exception.
The catch block is used to handle the exception thrown by try block and we can do any operations like giving proper messages within the catch block based on the exception object.
Let us go through some examples to understand it clearly:
Case 1: Using simple try-catch block to handle Exception
public class ExceptionTryCatchDemo { public static void main(String[] args) { try { Files.readAllBytes(Paths.get("C:/myfile.txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
PrintStackTrace prints the stack trace of the exception along with the line number and reason for it.
Case 2: Using simple try-catch-finally block to handle Exception.
public class ExceptionTryCatchDemo { public static void main(String[] args) { try { System.out.println("In try block "); Files.readAllBytes(Paths.get("C:/myfile.txt")); } catch (IOException e) { System.out.println("In Catch Block"); // TODO Auto-generated catch block e.printStackTrace(); }finally { System.out.println("In Finally Block"); } } }
In Try block about to throw exception
In Catch block
In Finally
If we run the following code with the correct file path we get:
In Try block about to throw exception
In Finally
So finally is the block of code which executes irrespective of the fact whether try block throws an error or not. It is very useful when we want to close some resources like in case of Database connections. If we are connection to database and some exception occurs during the execution,the connection needs to be closed to avoid resource leak. In such situation finally block comes into picture. We put the connection close code inside finally block. Finally block always executes before exiting the try-catch code block. So we use this to close the resources.
Note: The only condition finally does not execute is if System.exit is called.
Case 3: Declaring exception using throws clause.
Apart from handling the exception we can simply declare that this method can throw an exception using throws clause as part of method signature.
Declaring a throws clause in method signature puts a notice to the method using it that’ hey since I (method that is throwing exception) has not handled the exception you need to be careful and handle the exception or declare it for others to know that I can be dangerous if not handled properly.
Eg:
public class ExceptionTryCatchDemo { public static void main(String[] args) throws IOException { Files.readAllBytes(Paths.get("C:/myfile.txt")); } }
Using throws clause has many conditions and possible implications.
1. If we just keep on declaring the exceptions and no method handles it then the program application will fail without the exception being handled which could have been.
2. If we declare throws clause and the method which throws the exception throws an exception of type Exception class, the method calling this method can handle or declare only Exception class or throwable.
So to conclude the calling method can either declare same or superclass of the exception declared by called method.
3. In case of method overriding, if the overridden method throws and exception, the overriding method can either choose not to throw an exception or can throw same or superclass of the exception declared by called method.
We can create custom exception by simply extending Exception class.
Eg
public class MyException extends Exception { }And we can use it using throws clause:
try { throw new MyException(); //List<String> lines = Files.readAllLines(Paths.get("D:/myfile.txt")); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); }
Exercise to be tried:
What will be the output of following?
1.
try { throw new MyException(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }2.
try { throw new Exception(); } catch (MyException e) { // TODO Auto-generated catch block e.printStackTrace(); }
I hope you will like this :
If you want to learn other important core java topics you can check below links
- Making Games With Java- Introduction
- Getting Everything you need for Java
- Introduction to Java Programming
- Basic data types and Variables in java
- Basic Data types and Variables in java - Continued...
- User Input using Scanner class in java
- Conditional Logic in java
- Loops in java
- Arrays in java
- Wrapper classes in java
- Methods in java
Share it your colleagues if you like these articles.
Thanks for reading
0 comments:
Post a Comment