
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Checked vs Unchecked Exceptions in Java Programming
Checked exceptions
A checked exception is an exception that occurs at the compile time, these are also called as compile-time exceptions. These exceptions cannot simply be ignored at the time of compilation; the programmer should take care of (handle) these exceptions.
When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after the execution of the complete program.
Example
import java.io.File; import java.io.FileInputStream; public class Test { public static void main(String args[]){ System.out.println("Hello"); try{ File file =new File("my_file"); FileInputStream fis = new FileInputStream(file); } catch(Exception e){ System.out.println("Given file path is not found"); } } }
Output
Hello Given file path is not found
unchecked exceptions
A Run time exception or an unchecked exception is the one that occurs at the time of execution. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation.
IndexOutOfBoundsException, ArithmeticException, ArrayStoreException and, ClassCastException are the examples of run time exceptions.
Example
In the following Java program, we have an array with size 5 and we are trying to access the 6th element, this generates ArrayIndexOutOfBoundsException.
public class ExceptionExample { public static void main(String[] args) { //Creating an integer array with size 5 int inpuArray[] = new int[5]; //Populating the array inpuArray[0] = 41; inpuArray[1] = 98; inpuArray[2] = 43; inpuArray[3] = 26; inpuArray[4] = 79; //Accessing index greater than the size of the array System.out.println( inpuArray[6]); } }
Output
Run time exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at July_set2.ExceptionExample.main(ExceptionExample.java:14)