Вы находитесь на странице: 1из 19

Java Exception:

Exception:

 Dictionary meaning is abnormal condition


 An exception is an event that terminates the programs abnormally is called as an
exception.These exceptions occurred at runtime execution
 An unexpected event that terminates the flow of the programs.
 An exception is an event that terminates the normal flow of program is called as
exception. When an exception occurred (raised) the rest of the code will not executed.

To overcome these exception handle the exceptions.

How to handle the 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.

To handling the exception have two approaches:


1. try-catch block
2. throws

How many keywords used to handle the exception in java?

Ans: Five

They are: 1) Try 2) catch 3) finally 4) throw 5) throws


There are two types of exceptions in java:

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.

Examples for the unchecked exceptions are:

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:

C:\Users\Admin\Desktop\Java Exceptions>javac JavaException.java


C:\Users\Admin\Desktop\Java Exceptions>java JavaException
Hi JAVA-1
Hi JAVA-2
Exception in thread "main" java.lang.ArithmeticException: / by zero
at JavaException.main(JavaException.java:7)

If we are dividing any number by zero that produces the exception at runtime that is
ArithmeticException.

Example 2:ArrayIndexOutOfBoundsException

public class MyClass


{
public static void main(String[] args)
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
System.out.println("Something went wrong.");
}
}

After Executing we get an exception is:

C:\Users\Admin\Desktop\Java Exceptions>javac MyClass.java

C:\Users\Admin\Desktop\Java Exceptions>java MyClass

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:


10

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:

C:\Users\Admin\Desktop\Java Exceptions>javac NullPoiter.java

C:\Users\Admin\Desktop\Java Exceptions>java NullPoiter

Exception in thread "main" java.lang.NullPointerException

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:

C:\Users\Admin\Desktop\Java Exceptions>javac NumberFormatException.java


C:\Users\Admin\Desktop\Java Exceptions>java NumberFormatException
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at NumberFormatException.main(NumberFormatException.java:8)

The above examples are the unchecked exceptions caught at runtime.

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.

To handle this type of exception we have to approaches:

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:

C:\Users\Admin\Desktop\Java Exceptions>javac IOExceptions.java


IOExceptions.java:7: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
FileReader file = new FileReader("C:\\test\\a.txt");
1 error
What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

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.

Java Exception Keywords

There are 5 keywords which are used in handling exceptions in Java.

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.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It doesn't throw an


exception. It specifies that there may occur an exception in the method. It is
always used with method signature.
Common Scenarios of Java Exceptions
There are given some scenarios where unchecked exceptions may occur. They are as follows:

1) A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs

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

3) A scenario where NumberFormatException occurs

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

4) A scenario where ArrayIndexOutOfBoundsException occurs

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException
try and catch block

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.

Important points about try block

 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.

catch block important points


 Catch block will execute exception occurs in try block.
 You can write multiple catch blocks for generating multiple user friendly error
messages to make your application strong. You can see below example.
 At a time only one catch block will execute out of multiple catch blocks.
Example without Exception Handling
Example

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

Denominator not be zero

Multiple catch block

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

Denominator not be zero


Example 2:
class MultipleCatchBlock2
{
public static void main(String[] args)
{
try
{
int a[]=new int[5];
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

OUTPUT:
ArrayIndexOutOfBounds Exception occurs

rest of the code


Example 3:
public class MultipleCatchBlock3
{
public static void main(String[] args)
{
Try
{
String s=null;
System.out.println(s.length());
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}

OUTPUT:
Parent Exception occurs

rest of the code


Example 4:
class MultipleCatchBlock4
{
public static void main(String args[])
{
try
{
int x=10/0;
}
catch(Exception e)
{
System.out.println("common task completed");
}

System.out.println("rest of the code...");


}
}

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.

That Exception root class contains all type of exceptions like;

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.

Example:- throw statement throw an predefined 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)

Example: - throw statement throw a user defined exception.


To achieve this mechanism first we must know how to create user defined exception
then we are able to use this throw keyword.

There are two types of exceptions present in the java language


1) Predefined Exceptions.
ArithmeticException, IOException, NullPointerException…………..etc

2) User defined Exceptions.(created by user)


InvalidAgeException, MyException…etc

Customization of exception handling :-( creation of predefined exceptions)

There are two types of user defined exceptions


1. User defined checked exception.
a. Default constructor approach.
b. Parameterized constructor approach.
2. User defined un-checked Exception.
a. Default constructor approach.
b. Parameterized constructor approach.

Creation of user defined checked Exception by using default constructor approach:-

Step-1:- create the user defined checked Exception


Normal java class will become Exception class whenever we are extends Exception
class.

InvaliedAgeException.java:-

public class InvalidAgeExcepiton extends Exception

//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.
}

// A Class that uses above MyException


public class Main
{
static void status(int age) throws InvalidAgeException
{
if(age>20)
{
System.out.println("Marry");
}
else
{
throw new InvalidAgeException();
}
}

public static void main(String args[]) throws InvalidAgeException


{
Scanner scr=new Scanner(System.in);
System.out.println("Enter ur age");
int age=scr.nextInt();
Main.status(age);
}
}

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.

step-1:- create the user defined checked exception class.


Normal java class will become checked exception class when we extend Exception
class.
InvalidAgeException.java
// A Class that represents user-defined exception using parameterized constructor.

import java.util.Scanner;
class InvalidAgeException extends Exception
{
public InvalidAgeException(String s)
{
super(s); // Call constructor of parent Exception
}
}

// A Class that uses above InvalidAgeException


public class Main
{
static void status(int age) throws InvalidAgeException
{
if(age>20)
{
System.out.println("Marry");
}
else
{
throw new InvalidAgeException("U r not eligible for marry");
}
}
// Driver Program
public static void main(String args[]) throws InvalidAgeException
{
Scanner scr=new Scanner(System.in);
System.out.println("Enter ur age");
int age=scr.nextInt();
Main.status(age); //calling status() method using classname.
}
}
OUTPUT:
Run 1: Run 2:
C:\Users\staff1\Desktop>javac C:\Users\staff1\Desktop>java Main
Main.java Enter ur age
C:\Users\staff1\Desktop>java Main 18
Enter ur age Exception in thread "main" InvalidAgeException: U r not eligible for
23 marry
Marry at Main.status(Main.java:24)
at Main.main(Main.java:33)

Вам также может понравиться