Test09

What is an exception?

An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. In such cases we get a system generated error message.
An exception can occur for many different reasons. Following are some scenarios where an exception occurs.
  • A user has entered an invalid data.
  • A file that needs to be opened cannot be found.
  • A network connection has been lost in the middle of communications or the JVM has run out of memory.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Hierarchy of Java Exception classes:

Types of exceptions

There are two types of exceptions in Java:
1)Checked exceptions
2)Unchecked exceptions

Checked exceptions

All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in the program, you will get compilation error. For example, SQLException, IOException, ClassNotFoundException etc.

Unchecked Exceptions

Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

ArithmeticExceptionExample:

int a=10;
int b=0;
int c=0;
try {
   c=a/b; //risk statement
}
catch(ArithmeticException e) {
   System.out.println(e.getMessage());
   System.out.println("Change value of a ,a value can not be zero");
}
finally {
   System.out.println("Complete");
}

Output:

/by zero

Change value of a ,a value can not be zero

Complete

NullPointerExceptionExample:

String s=null;
try {
System.out.println(s.length());
}
catch (NullPointerException e) {
System.out.println(e.getMessage());
System.out.println("The value of s is null");
}

/by zero

Change value of a ,a value can not be zero

 

Visited 1 times, 1 visit(s) today

Comments are closed.

Close