0
Sponsored Links


Ad by Google
In this tutorial, I shall try to explain What is Checked Exception? and Example using Checked Exception. This topic is also  popular in java interview question for freshers as well as below 5 years of experienced profile like Why String is immutable and What is Serialization in java

What is Checked Exception?
Checked Exceptions are those exception which are forced by java compiler to catch it or throws it otherwise program will not compile.
All exceptions are checked exceptions, except for the sub classes of java.lang.Error and java.lang.Runtime class.

You can read more about What is Exception in java and Exception Hierarchy from my previous post.

Example of Checked Exception - Trying to reading a file from your hard disk, but somehow file is not in placed, than you will get java.io.FileNotFoundException, That's why compiler forced you to catch the FileNotFoundException or throws it otherwise program will not compile.

Code without handling Checked Exception -
public static void readFie(String fileName) {
		File file = new File(fileName);
		FileReader fileReader = new FileReader(file);
	}
If you try to call this method in your main function, It will gives you the below error message.
OUT PUT -
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException

at yourpacke.Yourclass.readFie(Yourclass.java:10)
at yourpacke.Yourclass.main(Yourclass.java:14)

OK, Now fixed the exception using below example

public static void readFie(String fileName) {
		File file = new File(fileName);
		try {
			FileReader fr = new FileReader(file);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

Few examples of Checked Exceptions -
  • IOException
  • FileNotFoundException
  • DataFormatException
  • XPathException
  • SQLException
  • TimeoutException
  • InterruptedException

That's it for the Checked Exceptions.
Sponsored Links

0 comments:

Post a Comment