0% found this document useful (0 votes)
2 views31 pages

UNIT 3 Module1

The document outlines the fundamentals of exception handling in Java, detailing exception types, keywords, and methods for managing exceptions. It explains the importance of handling exceptions to maintain program flow and provides examples of checked and unchecked exceptions. Additionally, it covers user-defined exceptions and the structure of try-catch blocks for effective error management.

Uploaded by

suganthi vasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views31 pages

UNIT 3 Module1

The document outlines the fundamentals of exception handling in Java, detailing exception types, keywords, and methods for managing exceptions. It explains the importance of handling exceptions to maintain program flow and provides examples of checked and unchecked exceptions. Additionally, it covers user-defined exceptions and the structure of try-catch blocks for effective error management.

Uploaded by

suganthi vasu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Regulation: IFETCER-2019 Academic Year: 2023-2024

IFET COLLEGE OF ENGINEERING


(An Autonomous Institution)
DEPARTMENT OF ELECTRICAL AND ELECTRONICS ENGINEERING
19UCSES401 - FUNDAMENTALS OF OBJECT ORIENTED PROGRAMMING
UNIT III- EXCEPTION HANDLING
Exceptions - exception hierarchy – exception types – using try and catch – multiple catch clauses – Nested try
statements – throw – throws – finally – built-in exceptions – creating own exceptions. Activity: Handling
ArrayIndexOutOfBound exception, User defined exception for invalid age for voting system

3.1. EXCEPTIONS
 An exception is a problem that arises during the execution of a program. When an Exception occurs
the normal flow of the program is disrupted and the program/Application terminates abnormally,
which is not recommended, therefore, these exceptions are to be handled.
 An exception can occur for many different reasons. Following are some scenarios where an exception
occurs.
o A user has entered an invalid data.
o A file that needs to be opened cannot be found.
o A network connection has been lost in the middle of communications or the JVM has run out of
memory.
Example:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;

Note: Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest
of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling,
the rest of the statement will be executed. That is why we use exception handling.

3.1.1. Java Exception Keywords


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.

1
Regulation: IFETCER-2019 Academic Year: 2023-2024

Syntax
try{
// code
}
catch(Exception_type1){
// catch block1
}
catch(Exception_type2){
//catch block 2
}
finally{
//finally blockalways execute
}

Fig3.1.1 Exceptions
Example:
public class Main {
public static void main(String[] args)
{ try {
int[] myNumbers = {1, 2, 3};
[Link](myNumbers[10]);
} catch (Exception e) {
[Link]("Something went wrong.");
} finally {
[Link]("The 'try catch' is finished.");
}
}
}
3.2 EXCEPTION HIERARCHY
 All exception classes are subtypes of the [Link] class. The exception class is a subclass of
the Throwable class. Other than the exception class there is another subclass called Error which is
derived from the Throwable class.
 Errors are abnormal conditions that happen in case of severe failures, these are not handled by the Java
programs. Errors are generated to indicate errors generated by the runtime environment. Example:
2
Regulation: IFETCER-2019 Academic Year: 2023-2024

JVM is out of memory. Normally, programs cannot recover from errors.


 The Exception class has two main subclasses: IOException class and RuntimeException Class.
I/O Exception Classes:
 Java I/OException is an exception when there is an issue with Input and Output operations in Java.
This exception is a checked exception that the programmer must explicitly handle.
Syntax of I/O Exception:
An IOException in Java is used and handled just like any other exception. The basic syntax for
handling an I/O Exception.
Syntax:
try {
// code that might throw an IOException
} catch (IOException e) {
// handle the exception
}
Causes of I/O Exception:
The following are few examples of I/O Exception.
 File or directory not found.
 Incorrect file permissions.
 Disk full or write-protected.
 Network or I/O device failure.
 Invalid user input.
Example:
public class InputMismatchExample1
{ public static void main(String[] args) {
// create scanner class object
Scanner sc = new Scanner([Link]);
// use try-catch block for taking input from the user and handling exception
try {
[Link]("Enter value of a to get its square value:");
Integer a = [Link](); // we give any float value as input
[Link]((a*a));
}
catch (InputMismatchException ex) {
[Link](ex);
}
}
}
Output:
Enter a value of a to get its square value:
2.3
[Link]

Runtime Exception:
RuntimeException is the superclass of all classes that exceptions are thrown during the normal operation
of the Java VM (Virtual Machine).
Example
public class TryCatchExample {
public static void main(String[] args) {
try {
int data=50/0; //may throw exception
3
Regulation: IFETCER-2019 Academic Year: 2023-2024

}
catch(ArithmeticException e){
[Link](e);
}
[Link]("rest of the code");
}
}
Output
[Link]: / by zero
rest of the code

Fig: 3.2 Exception Hierarchies


3.2.1 Exceptions Methods
[Link]. Method & Description
1 public String getMessage()
Returns a detailed message about the exception that has occurred. This message is
initialized in the Throwable constructor.
2 public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.

4
Regulation: IFETCER-2019 Academic Year: 2023-2024

3 public String toString()


Returns the name of the class concatenated with the result of getMessage().
4 public void printStackTrace()
Prints the result of toString() along with the stack trace to [Link], the error output
stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method
at the bottom of the call stack.
6 public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
Exception Methods with its Example used for Exception Hierarchy:
1. PrintStackTrace()
 The printStackTrace() method is defined in the Throwable class that belongs to [Link] package. The
method prints the name, description (such as / by zero), and the stack trace (line number and class
name where exception raised) of an exception.
 The stack trace traces where the next exception occurs.
 It is widely used to print the exception message.
Example:

public class ExceptionExample2


{
//user defined method
public static void divide()
{
try
{
//raised divide by zero exception
int a = 100/0;
}
catch (Exception e)
{
//prints exception message and detail of the exception
[Link]();
}
}
//main() method
public static void main(String args[])
{
//calling user defined method
divide();
}
}
Output:
[Link]: /By zero
2. Get Message() Method:
 The getMessage() method is also defined in the Throwable class that belongs to [Link] package.
 The method prints only the message of an exception.

5
Regulation: IFETCER-2019 Academic Year: 2023-2024

 It neither prints the name of the exception nor the description.


 It is widely used to print the exception message.
Syntax:
public String getMessage();
Example:
public class PrintExceptionMessage3
{
public static void main(String args[])
{
try
{
int a = 100/0;
}
catch (Exception e)
{
//prints only the message of the exception
[Link]([Link]());
//use the following statement if you want to print name of the exception and which exception thrown
//[Link](e);
}
}
}
Output:
/ By zero
3. ToString Method():
 The toString() method of the Throwable class overrides the toString() method of the Object class. It
prints the short description of an exception.
 It does not show the other information (like exception name and stack trace). It is not widely used to
print the exception message.
Example:
public class PrintExceptionMessage4
{
public static void main(String args[])
{
try
{
int a = 100/0;
}
catch (Exception e)
{
//we can use either of the statement to print the exception message
//both prints the same message
[Link]([Link]()); //[Link](e);
}
}
}
Output:
[Link]/ Byzero
4. GetCause()
The getCause() method of the Throwable class is used to retrieve the cause of a throwable, if any. This method
6
Regulation: IFETCER-2019 Academic Year: 2023-2024

is generally used to find the root cause of an error. If there are multiple causes for the error or exception, this
method returns the innermost cause.
Syntax:
public final Throwable getCause()
Example:
class GetCauseDemo {
public static void main(String args[])
{ try {
int a[] = new int[5];
a[-1] = 1;
} catch (Exception e){
Throwable t = new Throwable(" caused by access to invalid array length ",e);

// printing the cause


[Link]("Cause is:
"+[Link]());
}
}
}
Output:
Cause is: [Link]: -1
5. Get Stack Trace:
The getStackTrace() method of Java Throwable class is used to return an array of StackTraceElement given by
printStackTrace() method.
Syntax:
public StackTraceElement[] getStackTrace()
Example:
public class ThrowableGetStackTraceExample1
{ public static void main(String[] args) {
try{
int i=10/0;
}
catch(Exception e){
StackTraceElement[] trace = [Link]();
[Link](trace[0].toString());
[Link](trace[0].getClass());
[Link](trace[0].getMethodName());
[Link](trace[0].getFileName());
[Link](trace[0].getLineNumber());
}
}
}
Output:
class [Link]
main
[Link]
[Link]([Link])
4
3.3 EXCEPTION TYPES
 All exception types are subclasses of the built-in class Throwable. Thus, Throwable is at the top of
7
Regulation: IFETCER-2019 Academic Year: 2023-2024
the exception class hierarchy.

8
Regulation: IFETCER-2019 Academic Year: 2023-2024

 Immediately below Throwable are two subclasses that partition exceptions into two distinct branches.
One branch is headed by Exception. This class is used for exceptional conditions that user programs
should catch. This is also the class that you will subclass to create your own custom exception types.
 There is an important subclass of Exception, called Runtime Exception. Exceptions of this type are
automatically defined for the programs that you write and include things such as division by zero and
invalid array indexing.
 The other branch is topped by Error, which defines exceptions that are not expected to be caught
under normal circumstances by your program.
 Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the
run-time environment, itself. Stack overflow is an example of such an error. This chapter will not be
dealing with exceptions of type Error, because these are typically created in response to catastrophic
failures that cannot usually be handled by your program

Exception Types:
Java defines several types of exceptions that relates to various class [Link] are two major types of
[Link] also allows the user to define their own exceptions.

Fig: 3.3 Exception types


3.3.1 Checked Exception
 A checked exception is an exception that is checked (notified) by the compiler at compilation-time,
these are also called as compile time exceptions. These exceptions cannot simply be ignored, the
programmer should take care of (handle) these exceptions.
There are Six types of Checked Exception:
1)Class not Found Exception
2)Interrupted Exception
3)IO Exception
4)Instantiation Exception
5) SQL Exception
6) File not found Exception
Example
import [Link];
import [Link];

9
Regulation: IFETCER-2019 Academic Year: 2023-2024

public class FilenotFound_Demo


{ public static void main(String args[])
{
File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
}
}
Output
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr = new FileReader(file);
^
3.3.2 Unchecked Exception
 An unchecked exception is an exception that occurs at the time of execution. These are also called as
Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Types of Unchecked Exception:
1. Arithmetic Exception
2. Class cast Exception
[Link] Exception
4. ArrayIndexoutofBounds Exception
5. Array Store Exception
Example
public class Unchecked_Demo {
public static void main(String args[]) {
int num[] = {1, 2, 3, 4};
[Link](num[5]);
}
}
If we compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" [Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Error
 Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
3.3.3 User defined Exception:
Here are some rules to create Exception class in User-defined Exception:
1. Constructor: This is not mandatory in creating any constructor in the custom exception class. Providing
parameterized constructors in the custom exception class is a good practice.
2. Naming Convention: All exception classes are provided by the JDK end; hence, a custom exception should
follow a naming convention.
3. Extends Exception class: If the user is creating a custom exception class, then the user has to extend the
Exception class.

Syntax:
class SampleException{
public static void main(String args[]){
try{
10
Regulation: IFETCER-2019 Academic Year: 2023-2024
throw new UserException(<value>); // used to create new exception and throw

11
Regulation: IFETCER-2019 Academic Year: 2023-2024

}
catch(Exception e){
[Link](e);
}
}
}
class UserException extends Exception{
// code for exception class
}
Example:
Class SampleException{
public static void main(String args[]){
try{
throw new UserException(400);
}
catch(UserException e){
[Link](e) ;
}
}
}
class UserException extends
Exception{ int num1;
UserException(int num2) {
num1=num2;
}
public String toString(){
return ("Status code = "+num1) ;
}
}
3.4. USING TRY AND CATCH

3.4.1. Try-block:
 The code which might raise exception must be enclosed within try-block in the program.
 The try-block must be followed by either catch-block or finally-block at the end of the program.
 If both present, it is still valid but the sequence of the try-catch-finally block is the flow which is used
for most of the programs.
 Otherwise, compile-time error will be thrown for invalid sequence.
 The valid combination like try-catch block or try-catch-finally blocks must reside inside Main
Method.
Note: The code inside try-block must always be wrapped inside curly braces, even if it contains just
one line of code; Otherwise, compile-time error will be thrown inside the compiler.
3.4.2 Catch-block:
 It contains handling code for any exception raised from corresponding try-block and it must be
enclosed within catch block
 The catch-block takes one argument which should be of type Throwable or one of its sub-
classes i.e.; class-name followed by a variable
 The variable contains exception information for exception raised from try-block.
 Note: The code inside catch-block must always be wrapped inside curly braces, even if it contains
just one line of code; Otherwise, compile-time error will be thrown.

12
Regulation: IFETCER-2019 Academic Year: 2023-2024

Example:
class Exc2 {
public static void main(String args[]) {
int d, a;
try {
// monitor a block of code.
d = 0;
a = 42 / d;
[Link]("This will not be printed.");
}
catch (ArithmeticException e) {
// catch divide-by-zero error
[Link]("Division by zero.");
}
[Link]("After catch statement.");
}
}
Output:
Division by zero.
After catch statement.
 Once an exception is thrown, program control transfers out of the try block into the catch block. Put
differently, catch is not “called,” so execution never “returns” to the try block from a catch.
 Thus, the line "This will not be printed." is not displayed. Once the catch statement has executed,
program control continues with the next line in the program following the entire try /catch
mechanism.

3.5 MULTIPLE CATCH CLAUSES


 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.
 At a time only one exception occurs and at a time only one catch block is executed.
 All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.
Syntax:
try{
//block of statements
}catch(Exception handler class subclass ){
} catch(Exception handler super class){
}

13
Regulation: IFETCER-2019 Academic Year: 2023-2024

Fig: 3.5 Multiple Catch Exception


Example:
class MultipleCatches {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
[Link](a[10]);
}
catch(ArithmeticException e)
{ [Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{ [Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e) {
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}

Output
Arithmetic Exception occurs
rest of the code
Note: When you use multiple catch statements, it is important to remember that exception subclasses must
come before any of their super classes. This is because a catch statement that uses a superclass will catch
exceptions of that type plus any of its subclasses. Thus, a subclass would never be reached if it came after its
superclass. Further, in Java, unreachable code is an error.
For example, consider the following program:
class SuperSubCatch {
public static void main(String args[])
{ try {

14
Regulation: IFETCER-2019 Academic Year: 2023-2024

int a = 0;
int b = 42 / a;
}
catch(Exception e) {
[Link]("Generic Exception catch.");
}
catch(ArithmeticException e) {
// ERROR – unreachable
[Link]("This is never reached.");
}
}
}
Note:
 If you try to compile this program, you will receive an error message stating that the second catch
statement is unreachable because the exception has already been caught.
 Since Arithmetic Exception is a subclass of Exception, the first catch statement will handle all
Exception-based errors, including Arithmetic Exception.
 This means that the second catch statement will never execute.

3.6 NESTED TRY STATEMENTS


 The try statement can be nested. That is, a try statement can be inside the block of another try. Each
time a try statement is entered, the context of that exception is pushed on the stack.
 If an inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match. This continues until one of the
catch statements succeeds, or until all of the nested try statements are exhausted.
 If no catch statement matches, then the Java run-time system will handle the exception. Here is an
example that uses nested try statements:
Syntax
try{
statement 1;
//try catch block within another try block
try{
statement 2;
//try catch block within nested try block
try {
statement 3;
}
catch(Exception e2){
//exception message
}
}
catch(Exception e1){
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3){
//exception message
}

15
Regulation: IFETCER-2019 Academic Year: 2023-2024

Example:
// An example of nested try statements.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
[Link]("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
[Link](e);
}

//inner try block 2


try{
int a[]=new int[5];

//assigning the value out of array bounds


a[5]=4;
}

//catch block of inner try block 2


catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("other statement");
}
//catch block of outer try block
catch(Exception e)
{
[Link]("handled the exception (outer catch)");
}

[Link]("normal flow..");
}
}
Output
Going to divide by 0
[Link]: /by zero
[Link]: Index 5 out of bounds for length5
Other statement
Normal flow..

16
Regulation: IFETCER-2019 Academic Year: 2023-2024

Difference between Nested Try and Multiple Catch Block:


Factor Nested Try Block Multiple Catch Block
Scope of Exception Handling In nested try-catch blocks, the inner In multiple catch blocks, each catch
try block handles exceptions block handles exceptions that occur
specific to its code, and if not in the corresponding code within the
caught, they propagate to the outer same try block.
try block.
Code Organization Nested try-catch blocks may lead to Multiple catch blocks provide a
more complex and less readable more straightforward and organized
code due to the indentation and structure, especially when dealing
nesting. with different types of exceptions.

Execution Flow In nested try-catch blocks, the inner In multiple catch blocks, only the
catch blocks are skipped if an first catch block that matches the
exception is caught in the outer exception type is executed.
block.

3.7 THROW CLAUSE:


 The Java throw keyword is used to explicitly throw an exception.
 We can throw either checked or unchecked exception in java by throw keyword. The throw keyword
is mainly used to throw custom exception. We will see custom exceptions later.
Syntax
throw exception;
or
throw new IOException("sorry device error);
 Generally, throw keyword is used to throw user-defined exception or custom exception.
 Although, it is perfectly valid to throw pre-defined exception or already defined exception in Java like
IO Exception, Null Pointer Exception, Arithmetic Exception, Interrupted Excepting, Array Index Out
Of Bounds Exception, etc.
Example:
public class TestThrow {
//defining a method
public static void checkNum(int num)
{ if (num < 1) {
throw new ArithmeticException("\nNumber is negative, cannot calculate square");
}
else {
[Link]("Square of " + num + " is " + (num*num));
}
}
//main method
public static void main(String[] args)
{ TestThrow obj = new TestThrow();
[Link](-3);
[Link]("Rest of the
code..");
}
}

17
Regulation: IFETCER-2019 Academic Year: 2023-2024

Output:
Number is negative,cannot calculate square
at [Link]([Link])
at [Link]([Link])
3.8 THROWS CLAUSE:
 The Java throws keyword is used to declare an exception. It gives information to the programmer that
there may occur an exception so it is better for the programmer to provide the exception handling
code so that normal flow can be maintained.
Syntax
return_type method_name() throws exception_class_name{
//method code
}
 Throws keyword is used to declare the exception that might raise during program execution
 Whenever exception might thrown from program, then programmer doesn’t necessarily need to handle
that exception using try-catch block instead simply declare that exception using throws clause
next to method signature
 But this forces or tells the caller method to handle that exception; but again caller can handle that
exception using try-catch block or re-declare those exception with throws clause
 Note: use of throws clause doesn’t necessarily mean that program will terminate normally rather it is
the information to the caller to handle for normal termination
 Any number of exceptions can be specified using throws clause, but they are all need to be
separated by commas (,)
 throws clause is applicable for methods & constructor but strictly not applicable to classes
 It is mainly used for checked exception, as unchecked exception by default propagated back to the
caller (i.e.; up in the runtime stack)
Example
import [Link];
class ExceptionHandling {
void method3() throws IOException {
throw new IOException("device error");// checked exception
}
void method2() throws IOException {
method3();
}
void method1()
{ try {
method2();
} catch (IOException exp)
{ [Link]("exception
handled");
}
}
public static void main(String args[])
{ ExceptionHandling obj = new
ExceptionHandling(); obj.method1();
[Link]("normal flow...");
}
}
Output
exception handled
18
Regulation: IFETCER-2019 Academic Year: 2023-2024
normal flow...

19
Regulation: IFETCER-2019 Academic Year: 2023-2024

3.8.1 Difference between throw and throws in Java


No. Throw throws
1) Java throw keyword is used to Java throws keyword is used to declare an exception.
explicitly throw an exception.
2) Checked exception cannot be Checked exception can be propagated with throws.
propagated using throw only.
3) Throw is followed by an instance. Throws is followed by class.
4) Throw is used within the method. Throws is used with the method signature.
5) You cannot throw multiple exceptions. You can declare multiple exceptions e.g.
public void method()throws IOException,SQLException.

3.9 FINALLY-BLOCK:
 Java finally block is a block that is used to execute important code such as closing connection, stream
etc.
 Java finally block is always executed whether exception is handled or not.
 Java finally block follows try or catch block.
Syntax:
try {
// code that may cause exceptions
} catch (ExceptionType ex) {
// exception handling code
} finally {
// code that will always be executed, whether an exception occurs or not
}
Example
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){
[Link](e);
}
finally{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Output
finally block is always executed
rest of the code...
Important points regarding finally block:
 A finally block must be associated with a try block, you cannot use finally without a try block.
You should place those statements in this block that must be executed always.
 In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block.

20
Regulation: IFETCER-2019 Academic Year: 2023-2024

 An exception in the finally block, behaves exactly like any other exception.
 The statements present in the finally block execute even if the try block contains control
transfer statements like return, break or continue.
Finally block when using return statement:
class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}
public static int myMethod()
{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}

Output:
This is Finally block
Finally block ran even after return statement
112
3.10 BUILT-IN EXCEPTIONS
 Java defines several exception classes inside the standard package [Link].
 The most general of these exceptions are subclasses of the standard type RuntimeException. Since
[Link] is implicitly imported into all Java programs, most exceptions derived from
RuntimeException are automatically available.
 Java defines several other types of exceptions that relate to its various class libraries.
 Following is the list of Java Unchecked RuntimeException.
Built-in Exceptions
Basically, built-in Exceptions are those exceptions that are pre-defined in Java Libraries. These are
the most frequently occurring Exceptions.
An example of a built-in exception can be ArithmeticException, it is a pre-defined exception in the
Exception class of [Link] package. These can be further divided into 2 types:
 Checked Exception
 Unchecked Exception

3.10.1 Checked Exception:


 Checked exceptions are those exceptions that are caught at the compile time, so such exceptions
lead us to a potentially recoverable state.
 The compiler forces us to handle it before compiling. We can use the throws keyword to specify
to the compiler that our code might have some compile-time exceptions, which can be caught at
runtime.

21
Regulation: IFETCER-2019 Academic Year: 2023-2024

Unchecked Exception:
S.
Exception Description
No.
1 ArithmeticException Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException Array index is out-of-bounds.
3 ArrayStoreException Assignment to an array element of an incompatible
type.
4 ClassCastException Invalid cast.
5 IllegalArgumentException Illegal argument used to invoke a method.
6 IllegalMonitorStateException Illegal monitor operation, such as waiting on an
unlocked thread.
7 IllegalStateException Environment or application is in incorrect state.
8 IllegalThreadStateException Requested operation not compatible with the current
thread state.
9 IndexOutOfBoundsException Some type of index is out-of-bounds.
10 NegativeArraySizeException Array created with a negative size.
11 NullPointerException Invalid use of a null reference.
12 NumberFormatException Invalid conversion of a string to a numeric format.
13 SecurityException Attempt to violate security.
14 StringIndexOutOfBounds Attempt to index outside the bounds of a string.
15 UnsupportedOperationException An unsupported operation was encountered.

 Following is the list of Java Checked Exceptions Defined in [Link].

[Link]. Exception Description


1 ClassNotFoundException Class not found.
2 Attempt to clone an object that does not implement the
CloneNotSupportedException Cloneable interface.
3 IllegalAccessException Access to a class is denied.
4 Attempt to create an object of an abstract class or
InstantiationException
interface.
5 InterruptedException One thread has been interrupted by another thread.
6 NoSuchFieldException A requested field does not exist.
7 NoSuchMethodException A requested method does not exist.

Example
class NullPointer_Demo {
public static void main(String args[])
{
try {
String a = null; // null value
[Link]([Link](0));
}
catch (NullPointerException e) {
[Link]("NullPointerException..");

22
Regulation: IFETCER-2019 Academic Year: 2023-2024

}
}
}

Output
NullPointerException..

Types of Checked Exception:


1. Class not found Exception:
 ClassNotFoundException exception is caused when the Java Virtual Machine is unable to find the
required class.
 This type of exception is generally thrown by [Link](), [Link]() or
[Link]() functions.
 Since this is a checked exception, we need to use the throws keyword to specify that this method may
cause the class not found exception, otherwise our code will not compile.
Code:
public class classNotFound
{
static String classname = "missingClass";
public static void main() throws ClassNotFoundException
{
[Link](classname);
}
}
Output:
[Link]: missingClass
Explanation:
If there is no class with the given name then this will cause the ClassNotFoundException, and it will
terminate the execution of our code.
2. Interrupted Exception:
 Threads are used in Java to improve the efficiency of the code by allowing it to do multiple
things together at the same time.
 Threads are extended from the predefined Thread class in Java.
 It provides various functions like sleep which allows us to temporarily stop the execution of the
thread (for the specified number of milliseconds).
 InterruptedException is thrown when a thread is sleeping, waiting, or occupied and it is disturbed.
class interruptException extends Thread
{
public void run()
{
try
{
// code causing the exception
[Link](1000);
}
/* we need to use try catch, because with run
* method we can not use throws */
catch (InterruptedException e)
{
[Link](e);

23
Regulation: IFETCER-2019 Academic Year: 2023-2024

}
}
public static void main()
{
interruptException obj = new interruptException();
[Link]();
[Link]();
}
}
Output:
[Link]: sleep interrupted

3. SQL Exception:
 SQLException is thrown if there is an error in database access or other database errors.
 To access the Database, we use various functions like Connection, DriverManager, and getConnection.
 If we want to access a database at some URL, now if that URL is not accessible to the code, then it will
throw the SQLException.
We will use throws to handle the SQLException.
Example:
public class sqlexception
{
public static void main() throws SQLException
{
Connection conn = [Link]("Database_URL");
}
}
Output:
[Link]: No suitable driver found for Database_URL
4. I/O Exception:
 IOException is one of the most commonly handled exceptions.
 It is thrown when there is some sort of discrepancy in Input or Output. Using throws suppresses it
and not using throws will give a compile-time error.
Example:
class Main {
public static void main(String[] args) {
try {
// Creating an instance of FileReader class
FileReader fileReader = new
FileReader("[Link]");
[Link]([Link]());
[Link]();
}
catch (IOException e) {
[Link](e);
}
}
}
Output:
[Link]: [Link] (No such file or directory)

3.10.2 Unchecked Exceptions:


 An Unchecked Exception is an exception that can only be thrown at the run time (during
24
Regulation: IFETCER-2019 Academic Year: 2023-2024
the execution of the code). These are also called Runtime Exceptions.

25
Regulation: IFETCER-2019 Academic Year: 2023-2024

 It includes logical errors, bugs, or improper use of functions.


 A code with unchecked exceptions compiles correctly. Arithmetic Exception is a perfect example
of unchecked exceptions.
 A code that divides a number by 0 compiles without throwing any problems, but it throws
an Arithmetic Exception upon execution.
Types of Unchecked Exceptions:
 Arithmetic Exception
 Classcast Exception
 Nullpointer Exception
 Array Index out of bound Exception
1) Arithmetic Exception:
 An ArithmeticException is thrown when there is wrong arithmetic or mathematical operation done by
the code while executing.
 Divide by 0 is the most common type of wrong mathematical
operation. Example:
class arithmeticException
{
public static void main()
{
int a = 10, b = 0;
int c = a / b;
}
}
Output:
[Link]: / by zero
Since we are trying to divide 10 by 0, we are causing a mathematical error. This is predefined in the
ArithmeticException of Exception class in Java. Hence the code is throwing the exception.
2. Classcast Exception:
Type casting is changing the type from one type to another. Casting a class is changing its type.
ClassCastException is thrown by JVM when we try to cast a class from one type to another, and it violates
some rules.
Example:
import [Link].*;
public class classcastexception
{
public static void main()
{
String arr[] = new String[] {"Scaler", "Topics"};
ArrayList<String> to_list =
(ArrayList<String>)[Link](arr); [Link](to_list);
}
}
Output:
[Link]: class
Explanation:
Here we are trying to convert the string array to ArrayList. Since this type of operation is not supported by
the as List method, the code is throwing the ClassCastException.
3. NullPointer Exception:
NullPointerException is thrown by the JVM when we try to access a pointer that is pointing to Null (or
Nothing). Pointing to Null means that no memory is allocated to that specific object. Let us say we define a
26
Regulation: IFETCER-2019 Academic Year: 2023-2024

string as Null, and then try to access it, then JVM will throw the NullPointerException.
Output:
class nullpointerexception
{
public static void main()
{
String s = null;
[Link]([Link]());
}
}
Output:
[Link]
4. Array Index Out of Bounds Exception:
ArrayIndexOutOfBounds is one of the most common unchecked exceptions. It is thrown when we try to
access an array index that does not exist. Let us say that we have an array of size 10, and we try to access the
15th element. Then JVM will throw an ArrayIndexOutOfBounds exception.
Example:
class arrayindexoutofbounds
{
public static void main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
[Link](arr[15]);
}
}
Output:
[Link]: Index 15 out of bounds for length 10
3.11 CREATING OWN EXCEPTIONS
 If you are creating your own Exception that is known as custom exception or user-defined exception.
Java custom exceptions are used to customize the exception according to user need.
 By the help of custom exception, you can have your own exception and message.
3.11.1 Why use custom exceptions?
 Java exceptions cover almost all the general type of exceptions that may occur in the programming.
However, sometimes it is need to create custom exceptions.
 Following are few of the reasons to use custom exceptions:
o To catch and provide specific treatment to a subset of existing Java exceptions.
o Business logic exceptions: These are the exceptions related to business logic and workflow. It
is useful for the application users or the developers to understand the exact problem.
 In order to create custom exception, we need to extend Exception class that belongs to [Link]
package.

Example:
// [Link]
class InvalidAgeException extends
Exception{ InvalidAgeException(String s){
super(s);
}
}
// [Link]
class TestCustomException1{
27
Regulation: IFETCER-2019 Academic Year: 2023-2024

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}
catch(Exception m)
{ [Link]("Exception occured:
"+m);
}
[Link]("rest of the code...");
}
}
Output
Output:Exception occured: InvalidAgeException:not valid
rest of the code...

3.11.2 User Defined Exception using throws:


 There are certain Situations where there is possibility that a method might throw certain kinds of
exceptions but there is no exception handling mechanism present in the methods.
 The throws clause is used in such a situation. It is specified immediately after the method declaration
statement and just before the opening brace.

Example:
Class Examplethrows
{
Static void divide_m() throws ArithmeticException
{
Int x=22,y=0.z;
Z=x/y;
}
Public static void main(String args[])
{
Try
{
Divide_m();
}
Catch(Arithmetic Exception e)
{
[Link](“Caught the Exception”+e);
}
}
}
Output:
Caught the Exception [Link]: /by zero

28
Regulation: IFETCER-2019 Academic Year: 2023-2024

3.12.1 Activity: Handling ArrayIndexOutOfBound exception


The Exception used here is a type of builtin Exception which prints the corresponding
Exception to be handled safely.
Example:
public class ArrayIndexOutOfBoundsExceptionExceptionExample
{ public static void main(String[] args) {
String[] names = new
String[3]; names[0] =
"Sherlock"; names[1] =
"Watson"; names[2] = "Mary";
[Link](names[1]);
try {
[Link](names[4]);
}
catch (ArrayIndexOutOfBoundsException e) {
[Link]();
[Link]("The index used is out of the bounds of array.\n" + "Deal with it.");
}
[Link]("The execution of further statements continues.");
}
}
Output:
Watson
[Link]: 4
The index used is out of the bounds of array.
Deal with it.
The execution of further statements continues.

3.12.2 Activity:User defined exception for invalid age for voting system.
The User defined Exception has been described with another example called as age filtering for voting system
to allow only eligible voters.
Example:
Class InvalidAgeException extends
Exception{ InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{
static void validate(int age)throws InvalidAgeException{
if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}
catch(Exception m)
{ [Link]("Exception occured:
29
Regulation: IFETCER-2019 Academic Year: 2023-2024
"+m);

30
Regulation: IFETCER-2019 Academic Year: 2023-2024

}
[Link]("rest of the code...");
}
}
Output:
Output:Exception occured: InvalidAgeException:not valid
rest of the code...

31

You might also like