Java Exception
Java Exception
Exception:
Exception handling:
An exception is an event that terminates the program normally and remaining code
will executed.
Main objective:
The main objective of the handling the exception is to get the normal termination of the
program and rest of code will executed.
Ans: Five
1. Un-checked Exception:
An unchecked exception is an exception while execution the program the
compiler unable to check the exception is called as unchecked exception.
This exception occurred at runtime.
If the program is contains unchecked exception, but code is compiled and at
runtime JVM display the exception.
1. ArithmeticExcepption.
2. NumberNotFoundException.
3. NullPointerException.
4. ArrayIndexOutOfBoundsException.etc..
Examples 1:ArithmeticException
class JavaException
{
public static void main(String args[])
{
System.out.println("Hi JAVA-1 ");
System.out.println("Hi JAVA-2 ");
System.out.println(10/0);
System.out.println("Hi JAVA-3 ");
System.out.println("Hi JAVA-4 ");
}
}
In above example contains there are five statements and while executing the above
code the compiler unable to check the exception , code will compiled successfully
and at runtime JVM display the exception.
At the statement line no 3 will have an exception
System.out.println(10/0); //ArithmeticExcepption.
At statement-1 and statement -2 will executed and rest of code will not
executed. see below lines:
If we are dividing any number by zero that produces the exception at runtime that is
ArithmeticException.
Example 2:ArrayIndexOutOfBoundsException
at MyClass.main(MyClass.java:6)
Example 3: NullPointerException
class NullPoiter
{
public static void main (String[] args)
{
String str1 = null;
String str2 = “JAVA”;
if (str1.equals(str2))
{
System.out.print("Same");
}
else
{
System.out.print("Not Same");
}
}
}
After execution:
at NullPoiter.main(NullPoiter.java:13)
Example 4: NumberFormatException:
class NumberFormatException
{
public static void main (String[] args)
{
// Initializing String variable with null value
String str = null;
int i=Integer.parseInt(str);
System.out.println(i);
}
}
After Executing:
2. Checked Exception:
The checked exceptions are the exceptions which are checked by the compiler
it is called as checked exception, code will not compiled.
If the program is containing the checked exception code is not executed.
Example is :IOException, SQLException etc. Checked exceptions are checked
at compile-time.
1.try-catch block
2.throws
Example1: FileNotFoundException:
import java.io.*;
class IOExceptions
{
public static void main(String[] args)
{
FileReader file = new FileReader("C:\\Desktop\\a.txt");
}
}
After executing:
The core advantage of exception handling is to maintain the normal flow of the
application. An exception normally disrupts the normal flow of the application that is why
we use exception handling.
Keyword Description
try The "try" keyword is used to specify a block where we should place
exception code. The try block must be followed by either catch or finally. It
means, we can't use try block alone.
catch The "catch" block is used to handle the exception. It must be preceded by try
block which means we can't use catch block alone. It can be followed by
finally block later.
finally The "finally" block is used to execute the important code of the program. It
is executed whether an exception is handled or not.
int a=50/0;//ArithmeticException
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length());//NullPointerException
The wrong formatting of any value may occur NumberFormatException. Suppose we have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.
String s="abc";
int i=Integer.parseInt(s);//NumberFormatException
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
try block
Inside try block we write the block of statements which causes executions at run time in
other words try block always contains problematic statements.
The "try" keyword is used to specify a block where we should place exception code. The
try block must be followed by either catch or finally. It means, we can't use try block
alone.
If any exception occurs in try block then CPU controls comes out to the try block and
executes appropriate catch block.
After executing appropriate catch block, even though we use run time statement, CPU
control never goes to try block to execute the rest of the statements.
Each and every try block must be immediately followed by catch block that is no
intermediate statements are allowed between try and catch block.
Syntax
try
{
.....
}
catch()
{
....
}
Each and every try block must contains at least one catch block. But it is highly
recommended to write multiple catch blocks for generating multiple user friendly error
messages.
One try block can contains another try block that is nested or inner try block can be
possible.
Nested try block syntax:
Syntax
try
{
.......
try
{
.......
}
}
catch block
Inside catch block we write the block of statements which will generates user friendly
error messages.
The "catch" block is used to handle the exception. It must be preceded by try block which
means we can't use catch block alone. It can be followed by finally block later.
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0;
b=a/0;
System.out.println("Denominator not be zero");
}
}
Abnormally terminate program and give a message like below, this error message is not
understandable by user so we convert this error message into user friendly error message,
like "denominator not be zero".
Example of Exception Handling
Example:
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0;
try
{
b=a/0;
}
catch (ArithmeticException e)
{
System.out.println("Denominator not be zero");
}
}
}
Output
You can write multiple catch blocks for generating multiple user friendly error messages
to make your application strong. You can see below example.
A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.
Points to remember
o At a time only one exception occurs and at a time only one catch block is executed.
o All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Syntax is:
try
{
//Exception code
}
catch(exception_name ref-var)
{
//Handling errors
}
catch(exception_name ref-var)
{
//Handling errors
}
---------------------------------------------------------
Example: 1
class ExceptionDemo
{
public static void main(String[] args)
{
int a=10, b=0, div;
try
{
div=a/b;
System.out.println("Result: "+div);
}
catch(ArithmeticException ae)
{
System.out.println("Denominator not be zero");
}
catch(Exception e)
{
System.out.println("Enter valid number");
}
}
}
Output
OUTPUT:
ArrayIndexOutOfBounds Exception occurs
OUTPUT:
Parent Exception occurs
OUTPUT:
Common task completed
Rest of the code…..
Note:
catch(Exception e)
{
System.out.println("common task completed");
}
Here Exception is a root class for all exceptions. If any exception occur in try automatically
executed this above catch block.
1. ArithmeticException
2. ArrayIndexOutOfBoundException
3. FileNotFoundException
User-defined Custom Exception in Java
Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
Throw keyword:-
It is used to handover user created Exception object to JVM.
It is used to throw exception explicitly.
By using throw keyword it is possible throw predefined Exceptions & custom exception
but it is always recommended to throw custom exceptions.
Note: - throw keyword is used to handover user created exception object to JVM whether it is
predefined exception class or user defined exception class but it is always recommended
throw custom exception.
Step 1:- create the Exception object explicitly by the developer by using new keyword.
new InvalidAgeException("Shridhar not eligible");
Step 2:- handover (throw) user created Exception object to jvm by using throw keyword.
throw new InvalidAgeException ("Shridhar not eligible");
Example:-
import java.util.*;
class Test
{
static void status(int age)
{
if (age<18)
{
throw new InvalidAgeException("not eligible for vote");
}
else
{
System.out.println("welcome to the voting");
}
}
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("please enter your age ");
int age=s.nextInt();
Test.status(age);
System.out.println("rest of the code");
}
}
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Desktop>javac Test.java C:\Users\staff1\Desktop>java Test
C:\Users\staff1\Desktop>java Test please enter your age
please enter your age 12
26 Exception in thread "main"
welcome to the voting java.lang.ArithmeticException: not eligible for vote
rest of the code at Test.validate(Test.java:8)
at Test.main(Test.java:19)
InvaliedAgeException.java:-
//default constructor
}
Example to create user defined exception by using default constructor.
// A Class that represents user-defined exception using parameterized constructor.
import java.util.Scanner;
class InvalidAgeException extends Exception
{
//Default Constructor.
}
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Documents>javac Test.java C:\Users\staff1\Documents>java Test
C:\Users\staff1\Documents>java Test Enter ur age
Enter ur age 15
23 Exception in thread "main" InvalidAgeException
Marry at Test.status(Test.java:19)
at Test.main(Test.java:28)
Example :- Creation of user defined checked exception by using parameterized constructor
approach.
import java.util.Scanner;
class InvalidAgeException extends Exception
{
public InvalidAgeException(String s)
{
super(s); // Call constructor of parent Exception
}
}