0% found this document useful (0 votes)
4 views

Exception Handling - Google Docs

The document explains the differences between errors and exceptions in programming, detailing compilation errors (lexical, syntax, semantic) and runtime errors. It describes exceptions as runtime errors that can be handled programmatically, categorizing them into predefined and user-defined exceptions, with further distinctions between checked and unchecked exceptions. Additionally, it provides examples of common exceptions in Java, such as ArithmeticException and NullPointerException, and emphasizes the importance of proper exception handling to avoid abnormal terminations in applications.

Uploaded by

Naru Sonawane
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)
4 views

Exception Handling - Google Docs

The document explains the differences between errors and exceptions in programming, detailing compilation errors (lexical, syntax, semantic) and runtime errors. It describes exceptions as runtime errors that can be handled programmatically, categorizing them into predefined and user-defined exceptions, with further distinctions between checked and unchecked exceptions. Additionally, it provides examples of common exceptions in Java, such as ArithmeticException and NullPointerException, and emphasizes the importance of proper exception handling to avoid abnormal terminations in applications.

Uploaded by

Naru Sonawane
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/ 11

Exception Handling:

—------------------
Q)What is the difference between Error and Exception?
—------------------------------------------------------
Ans:
—---
Error is a problem , it will not allow us to execute applications.

There are two types of Errors.

1. Compilation Errors
2. Runtime Errors

Compilation Errors:
These errors are generated at compilation time.
There are three types of Compilation Errors.
1. Lexical Errors
2. Syntax Errors
3. Semantic Errors

Lexical Errors:
These errors are identified by the Lexical Analysis phase in Compilation.
EX: Mistakes in the tokens
EX: int i = 10; —---> Valid
nit i = 10; —---> Invalid, Lexical Error

EX: for(int i = 0; i < 10; i++){


}
Status: Valid
fro(int i = 0; i < 10; i++){
}
Status: Invalid, Lexical Error.

Syntax Errors:
These errors are identified in the Syntax Analysis phase in Compilation.
EX: Mistakes in the syntaxes.
EX: int i = 10; —-> Valid
i 10 int; —---> Invalid, Syntax Error
EX: while(i < 10){
Sopln(i);
}
Status: Valid
(i < 10) while{
Sopln(i);
i = i + 1;
}
Status: Invalid, Syntax Error.

EX: int i = 10 —----> Syntax Error

Semantic Error:
These errors are identified in the Semantic Analysis phase in compilation.
EX: Meaningless statements.
EX: Providing incompatible operands for the operators.
EX: int i = 10;
boolean b = true;
char c = i + b;

Note: Along with the above three types of errors, all the programming
languages are having their own errors as per the programming language rules
and regulations.

EX: Unreachable Statement


Variable i might not have been initialized.
Illegal Start of Expression
—----
—-----

Runtime Errors or Error:


These errors are identified at runtime.

The errors which are identified at runtime and which are not having solutions
programmatically then these errors are “Runtime Error”.

EX: Unavailability of IO Components.


EX: InsufficientMainMemory

Exception:
These are runtime errors identified at runtime and which are having solutions
programmatically.
EX: ArithmeticException
EX: NullPointerException
EX: FileNotFoundException
—----------------------------------------------------------------------------
Exception:
Exception is an unexpected event occurred at runtime of the application,
which may be provided by the users while entering dynamic input to the java
applications, which may be provided by the Databases when we perform database
operations from java applications in JDBC applications, which may be provided
by the network when we establish connection between client and Server in
Distributed applications,....... Causes abnormal termination to the
applications.

There are two types of Terminations for the applications,


1. Smooth Termination
2. Abnormal Termination

Smooth Termination: If the application execution is terminated at the end of


the program then that termination is “Smooth Termination”.

Abnormal Termination: If the application execution is terminated in the


middle of the program then that termination is called Abnormal Termination.

If the abnormal termination is available for the applications then it may


provide the following serious problems
1. It may Corrupt the local Operating System.
2. It may hang the network if it is a network based application.
3. It may down the server if it is a server side application.
4. It may collapse the Database if it is a database related applications
—----
—-----

To avoid the above serious problems , we have to avoid Abnormal Terminations


in our applications. To avoid abnormal terminations to our applications we
have to handle the exceptions properly , here to handle exceptions properly
we have to use a set of mechanisms explicitly called “Exception Handling
Mechanism”.

Java is a Robust Programming Language, because


1. Java has a very good memory management system in the form of Heap
memory management system, it is a dynamic memory management system , it
allocates and deallocates memory for the objects at runtime as per the
requirement.
2. Java has a very good Exception Handling mechanism , because Java has
provided a very good predefined library to represent and handle almost
all the exceptions which are coming frequently in Java applications.
There are two types of Exceptions in Java.
1. Predefined Exceptions
2. User defined Exceptions

Predefined Exceptions:
—----------------------
These exceptions are defined by the Java programming languages , Java has
provided predefined classes for these exceptions in java predefined library.

There are two types of predefined exceptions.


1. Checked Exceptions
2. Unchecked Exceptions

Q)What is the difference between Checked Exceptions and Unchecked Exceptions?


—----------------------------------------------------------------------------
Ans:
—---
1. If any exception is identified by the compiler at compilation time then
that exception is called Checked Exception.

Note: Really exceptions occur at runtime only, not at compilation time, but
Compiler can recognize some exceptions which are going to generate at runtime
then that exceptions are called “Checked Exceptions”.

If any exception is identified by the JVM at runtime , not by the compiler at


compilation time then that Exception is called “Unchecked Exception”.
2. RuntimeException and its subclasses, Error and its subclasses are the
examples for Unchecked Exceptions.

All the remaining Exceptions are the examples for Checked Exceptions.

There are two types of Checked Exceptions.


1. Pure Checked Exceptions
2. Partially Checked Exceptions

Q)What is the difference between Pure checked exceptions and Partially


Checked Exceptions?
—----------------------------------------------------------------------------
Ans:
—----
If any checked Exception has only Checked Exceptions as subclasses then that
checked exception is called “Pure Checked exception”.
EX: IOException

If any checked exception has at least one subclass as an unchecked exception


then that checked exception is called “Partially Checked Exception”.
EX: Exception, Throwable

Overview of Predefined Exceptions:


—-------------------------------------
1. ArithmeticException:
If we divide any number by zero then JVM will raise ArithmeticException.
EX:
public class Main {
public static void main(String[] args) {
int i = 100;
int j = 0;
float f = i/j;
System.out.println(f);
}
}

If we run the above program then JVM will provide the following exception
message.

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


at Main.main(Main.java:5)

The above Exception message is divided into the following three parts.
1. Exception Name : java.lang.ArithmeticException
2. Exception Description : / by zero
3. Exception Location : Main.java: 5

2. NullPointerException:
If we access any instance variable or instance method on a reference variable
containing null value then JVM will raise NullPointerException.

EX:
import java.util.Date;

public class Main {


public static void main(String[] args) {
Date date = null;
System.out.println(date.toString());
}
}

If we run the above program then JVM will provide the following exception
details.
1. Exception Name: java.lang.NullPointerException
2. Exception Description : Cannot invoke "java.util.Date.toString()" because
"date" is null
3. Exception Location: Main.java: 6

3. ArrayIndexOutOfBoundsException:
In Java applications, when we access an element from an array on the basis of
the index value , when we insert an element in an array on the basis of the
index value, where the provided index value is in the outside range of array
indexes there JVM will raise ArrayIndexoutOfBoundsException.
EX:
import java.util.Date;

public class Main {


public static void main(String[] args) {
int[] a = {1,2,3,4,5};
System.out.println(a[2]);// 3
System.out.println(a[4]);// 5
System.out.println(a[10]);
}
}
If we run the above program then JVM will provide the following Exception
details.

1. Exception Name : java.lang.ArrayIndexOutOfBoundsException


2. Exception Description : Index 10 out of bounds for length 5
3. Exception Location : Main.java: 7

4. StringIndexOutOfBoundsException:
In Java applications , when we are performing String operations on the basis
of the index value , where the provided index value is in the outside range
of the String indexes there JVM will raise StringIndexOutOfBoundsException .
EX:
import java.util.Date;

public class Main {


public static void main(String[] args) {
String str = new String("Durgasoft");
System.out.println(str.charAt(6));
System.out.println(str.charAt(20));
}
}

If we run the above program then JVM will provide the following exception
details.

1. Exception Name : java.lang.StringIndexOutOfBoundsException


2. Exception Description: String index out of range: 20
3. Exception Location : Main.java: 7

5. ClassNotFoundException:
In Java applications, if we want to load a particular class bytecode to the
memory then we will use the Class.forName() method.

Class cls = Class.forName(“Employee”);

JVM will search for Employee.class at the current location, at the predefined
library and at the locations referred by the classpath environment variable.

If the required Employee.class file is not available at all the above


locations then JVM will raise a ClassNotFoundException.
EX:
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
}
}

If we run the above program then JVM will provide the following exception
details.

1. Exception Name : java.lang.ClassNotFoundException


2. Exception Description : Employee
3. Exception Location : Main.java: 4

6. InstantiationException:
In Java applications, by using Class.forName() method we are able to load a
particular class bytecode to the memory, after loading class bytecode if we
want to create an object for the loaded class we have to use the following
method java.lang.Class.

public Object newInstance()throws InstantiationException,


IllegalAccessException

Class cls = Class.forName(“Employee”);


Employee emp = (Employee) cls.newInstance();

If we execute the above instruction, JVM will search for a 0-arg constructor
in the Employee class. If no 0-arg constructor is available in the Employee
class then JVM will raise InstantiationException .

EX:
class Employee{
Employee(int i){
System.out.println("Employee-Constructor");
}
}
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
Employee employee = (Employee) cls.newInstance();
}
}

If we run the above program then JVM will provide the following details
1. Exception Name: java.lang.InstantiationException
2. Exception Description : Employee
3. Exception Location : Main.java: 9

7. IllegalAccessException:
In Java applications, by using Class.forName() method we are able to load a
particular class bytecode to the memory, after loading class bytecode if we
want to create an object for the loaded class then we have to use the
following method from java.lang.Class.

public Object newInstance()throws InstantiationException,


IllegalAccessException

Class cls = Class.forName(“Employee”);


Employee emp = (Employee) cls.newInstance();

If we execute the above instruction, JVM will search for a non private
constructor in the Employee class. If we have a private constructor in the
Employee class then JVM will raise IllegalAccessException .
EX:
class Employee{
private Employee(){
System.out.println("Employee-Constructor");
}
}
public class Main {
public static void main(String[] args) throws
Exception {
Class cls = Class.forName("Employee");
Employee employee = (Employee) cls.newInstance();
}
}

If we run the above code then JVM will provide the following exception
details.
Exception Name : java.lang.IllegalAccessException
Exception Description : class Main cannot access a member of class Employee
with modifiers "private"
Exception Location : Main.java: 9

8. ClassCastException:
In Java applications, we are able to keep subclass object reference value in
superclass reference variable, but we are unable to keep superclass object
reference value in subclass reference variable, if we keep superclass object
reference value in subclass reference variable then JVM will raise
ClassCastException.

EX:
class Employee{

}
class Manager extends Employee{

}
public class Main {
public static void main(String[] args) throws
Exception {
Employee employee = new Employee();
Manager manager = (Manager) employee;
}
}

If we run the above program then JVM will provide the following Exception
details.
1. Exception Name : java.lang.ClassCastException:
2. Exception Description : class Employee cannot be cast to class Manager
3. Exception Location : Main.java: 10

9. FileNotFoundException:
In Java applications, when we are trying to read data by using
FileInputStream or FileReader from a particular file and if the provided file
is not available then JVM will raise FileNotFoundException.
EX:
import java.io.FileInputStream;
public class Main {
public static void main(String[] args) throws
Exception {
FileInputStream fileInputStream = new
FileInputStream("E:/abc/welcome.txt");
}
}

If we run the above code then JVM will provide the following exception
details.

1. Exception Name : java.io.FileNotFoundException


2. Exception Description : E:\abc\welcome.txt (The system cannot find the
file specified)
3. Exception Location : Main.java: 5

‘throw’ Keyword:
—-----------------

You might also like