0% found this document useful (0 votes)
9 views10 pages

unit-3(part-1)

The document discusses exception handling in programming, explaining the types of exceptions: checked and unchecked. It details how to handle exceptions using try-catch blocks, the use of throw and throws keywords, and the significance of finally blocks. Additionally, it covers custom exceptions and provides examples of built-in exceptions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views10 pages

unit-3(part-1)

The document discusses exception handling in programming, explaining the types of exceptions: checked and unchecked. It details how to handle exceptions using try-catch blocks, the use of throw and throws keywords, and the significance of finally blocks. Additionally, it covers custom exceptions and provides examples of built-in exceptions in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

UNIT-3

PART-1:EXCEPTION HANDLING:
Exceptions: It is a runtime problem that occurs due to the abnormal statement or an abnormal
instruction.
Ex: int [] a={1, 2 , 3};
System.out.println(a[1]); // 2
System.out.println(a[3]);//ArrayIndexOutOfBoundsException
Exception Types:
Based on compiler awareness Exceptions can be classified into 2 types.
1. Checked Exceptions (Compiler Aware Exceptions)
2. Unchecked Exceptions. (Compiler Unaware Exceptions).
1. Checked Exceptions: The compiler aware Exceptions are known as CheckedException.
(OR)
1.The Exceptions which are known to compiler i.e., the Exceptions which occurs due to
usage of built-in members are known as checked exceptions.
2.It is mandatory to handle the checked exception either by catching it or throwing it.
Ex:-
1. FileNotFoundException.
2. InterruptedException.
3. SQLException.
4. IOException.
Unchecked Exception: the compiler unaware exception is known as unchecked exceptions.
(OR)
1.The exceptions which are not known to the compilers i.e., the exceptions which occurs due
to input (values or data) passed by the user are known as unchecked exceptions.
2. since they are not known to compiler it is not mandatory to handle the exceptions to go for
execution.
Ex:-
1. ClassCastException.
2. NullPointerException.
3. ArrayIndexOutOfBoundsException.
4. StringIndexOutOfBoundsException.
5. ArithmeticException.
Exception Handling: To handle the exception and complete the execution of program even
when we have abnormal statements inside my program. in two ways.
1. With the help of try and catch blocks
2. Declaring exception
Using try And Catch:
try catch block:
Syntax:
try
{
//abnormal statements;
}
catch(refrence variable for throwable type)
{
//Solution statements for exception;
}
Note: Catch block should be always present immediately after try block.
try: The statements responsible for exception to occur/abnormal statements must be written
inside try block.
When the exception occurs in try.
1. Execution of try block will be stopped
2. The reference of throwable type object is thrown to the catch block.
catch block:
catch block is used to handle the exception.
1. It is mandatory to declare a reference variable of throwable type
2. It is used to catch the reference of object thrown by try block.
3. We say exception is handled only when the object reference thrown from try is caught by
the catch block else it is not handled.

Note:
1. A catch block could catch only if the variable declared is either same type or super class
type of the throwable type of object.
2. A catch block gets executed only when the exception is caught.
Ex:-
class A
{
public static void main(String[] args)
{
try
{
System.out.println(1/0);
}
catch (ArithemticException a1)
{
System.out.println(“denominator should not be zero”);
}
}
}
try with multiple catch():
Syntax:
Try
{
abnormal statements;
}
Catch(refrence of throiwable type)
{
//statements;
}
Catch(refrence of throiwable type)
{
//statements;
}
Catch(refrence of throiwable type)
{
//statements;
}
Note: -
1. Only one catch block can get executed
2. The exception object reference thrown by try moves in top to bottom order
3. The multiple catch blocks must be designed such that catch with sub class reference must
be in first place and then catch with super class reference must be at the bottom else we get
CTE.
Ex:-
class A
{
public static void main(String[] args)
{
try
{
int [] a = {1, 0, 2};
System.out.println(a[0]/a[1]);
System.out.println(a[4])
}
catch (ArithemticException a1)
{
System.out.println(“denominator should not be zero”);
}
catch(ArrayIndexOutOfBoundsException a2)
{
System.out.prinltn(“index exceeded”);
}
}
}
throw:
1. throw is a key word, which is used to raise our own exceptions.(Create a throwable
type object forcefully and stop the flow of program ).
2. syntax: throw create a throwable type Object
3. ex: throw new NegativeSalaryException();
throws:
1. throws is a key word, which is used to declare the Exceptions.
2. If a checked exception is not handled using, try and catch then it must be declared for
exception Object propagation.
Syntax:
[Modifiers] returntype methodname([Formal arguments]) throws Exception1,
Exception2,Exception3…..n { }

Note: If we call a method which declares the exception using throws key word then the
calling method must either handle it or throw it again else we get CTE.
Difference between throw and throws: -

finally:
1. it is a block of statements which gets executed mandatory irrespective of whatever
happens to the application.
2. finally, is a keyword.
3. A block which is prefix with just finally keyword is known as finally block.
4. A finally can be used along with following members.
 Only try block
 try and catch block
 try with multiple catch block
A finally block should always be return as the last block among all the cases.
Flow of execution for finally block:
1. exception doesn’t occur finally gets executed.
2. Exception occurs but not handled finally gets executed.
3. Exception occurs and is handled finally gets executed.
Ex:-
class p1
{
public static void main(String[] args)
{
try
{
System.out.println(1/0)
}
Finally
{
System.out.println(“bye”);
}
}
}
Custom Exceptions (User Defined Exceptions or Creating Own Exception classes):
The exception class created by the user is known as User defined Exceptions or Custom
Exceptions.
We can Create an exception class as follows;
1. Create a new class
2. Inherit any of the throwable type class.
Note:
1. If it inherits runtime exceptions or its sub classes, error or its subclasses it behaves
like unchecked exception.
2. If it inherits any other classes then it behaves like checked exception.
Ex:-
class NegativeSalaryException extends Exception
{
public String toString()
{
return "NegativeSalaryException: Salary cannot be negative.";
}
}

class Employee
{
String Ename;
int Eid;
double Esal;
public Employee(String Ename,int Eid,double Esal)throws NegativeSalaryException
{
if (Esal < 0)
{
throw new NegativeSalaryException();
}
this.Ename = Ename;
this.Eid=Eid;
this.Esal = Esal;
}
}
public class CustomException
{
public static void main(String[] args)
{
try
{
Employee emp1 = new Employee("sheela",123, -2500);
System.out.println("Employee created successfully!");
}
catch (NegativeSalaryException e)
{
System.out.println(e);
}
}
}
Built-in Exceptions:
Def: Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important built-
in exceptions in Java.
S.no Exception & Description
1. ArithmeticException
Arithmetic error, such as divide-by-zero.

2. ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3.
ClassCastException
Invalid cast.
4. IndexOutOfBoundsException
Some type of index is out-of-bounds.

5. NullPointerException
Invalid use of a null reference.

6. StringIndexOutOfBounds
Attempt to index outside the bounds of a string.

7. ClassNotFoundException
Class not found.

8. InterruptedException
One thread has been interrupted by another thread.

9. NegativeArraySizeException
Array created with a negative size.

1Example for ArithmeticException:--


class AE
{
public static void main(String args[])
{
System.out.println(2/0);
}
}
Output: -

Exception in thread "main" java.lang.ArithmeticException: / by zero


at com.tutorialspoint.ExcepTest.main(AE.java:5)
2Example for ClassCastException:---
class ClassCastExceptionExample
{
public static void main(String[] args)
{
Object obj = new Integer (100);
System.out.println((String) obj);
}
}
Output:
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.String
at ClassCastExceptionExample.main(ClassCastExceptionExample.java:4)
3Example for ArrayIndexOutOfBoundsException:----
class AI
{
public static void main(String[] args)
{
int a[]={1,2,4};
System.out.println(a[10]);
}
}

Output:---
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of
bounds for length 3
at AI.main(AI.java:6)

You might also like