Exception Handling
Exception Handling
Exception Handling
Types of Errors
Que:
1. List and explain different types of errors.
2. Explain types of errors with example.
3. List types of Errors in exceptional handling and explain any one of them.
4. List types of error in Java.
Ans:
There are basically three types of errors that may arise during computer programs
execution:
1. Syntax errors
2. Runtime errors
3. Logic errors
1. Syntax errors
Syntax Errors, also known as Compilation errors are the most common type of errors.
Most Syntax errors are caused by mistakes that you make when writing code.
Common examples are:
Misspelled variable and function names
Missing semicolons
Improperly matches parentheses, square brackets, and curly braces
Incorrect format in selection and loop statements
2. Runtime errors
Run-time errors are those that appear only after you compile and run your code. It will
occur when your program attempts an operation that is impossible to carry out.
You can fix most run-time errors by rewriting the faulty code, and then recompiling and
running it.
Common examples are:
Trying to divide by a variable that contains a value of zero
Trying to open a file that doesn't exist
There is no way for the compiler to know about these kinds of errors when the program is
compiled.
3. Logic errors
Your code may compile and run without any Syntax Errors or Run-time Errors, but the
output of an operation may produce unwanted or unexpected results in response to user
actions. These types of errors are called Logic Errors.
Common examples are:
Multiplying when you should be dividing
Adding when you should be subtracting
Opening and using data from the wrong file
Displaying the wrong message
Exception
Que:
1. Compare checked and Unchecked Exception.
Ans:
An exception (or exceptional event) 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
terminates abnormally.therefore, these exceptions are to be handled.
Following are some scenarios where an exception occurs.
A user has entered an invalid data.
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
1. Checked exceptions –
For example, if you use FileReader class in your program to read data
from a file, if the file specified in its constructor doesn't exist, then
a FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
2. Unchecked exceptions
3. Errors
Error is a problem that arises, which is not under the control of the user or
the programmer.
For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Que:
1. Explain Exception Handling.
2. Explain basic concept of Exception Handling.
Ans:
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
Program statements that you want to monitor forexceptions are contained within a try
block.
If an exception occurs within the try block, it isthrown. Your code can catch this
exception (using catch) and handle it.
System-generated exceptions are automatically thrown by the Java run-time system.
Tomanually throw an exception, use the keyword throw.
Any exception that is thrown out ofa method must be specified as such by a throws
clause.
Any code that absolutely must beexecuted after a try block completes is put in a
finallyblock.
This is the general form of an exception-handling block:
try
{
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
finally
{
// block of code to be executed after try block ends
}
Try…Catch
Que:
1. Explain Try and Catch with suitable example.
2. Explain ‘try’ and ‘catch’ statements in exceptional handling of Java language.
3. Write a program and explain try…catch block.
4. Explain ArrayIndexOutOfBound Exception in Java with example.
Ans:
Throw
System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, the throw keyword is used.
it is used to explicitly throw exception in java.
The general form of throw is shown here:
throw ThrowableInstance;
class throwDemo
{
static void validate(int age)
{
try
{
if(age<16)
{
throw new ArithmeticException("Invalid Age");
}
}
catch(ArithmeticException e)
{
e.printStackTrace();
}
}
validate(age);
}
}
Throws
The throws keyword is used to declare that a method may throw one or some
exceptions.
It can propagate exception to the calling method.
Calling method must have to catch the exception which is thrown by the throws
keyword.
Programmer hasto handle the thrown exception.
It can throws checked exception.
All other exceptions that a methodcan throw must be declared in the throws clause.
The throws keyword must be followed by Throwable class or one of its subclasses.
This is the general form of a method declaration that includes a throws clause:
catch(ArithmeticException e)
{
System.out.println("Please Enter Valid Data");
}
}
}
Finally
Finallycreates a block of code that will be executed after a try/catch block hascompleted.
The finally block willexecute whether or not an exception is thrown.
If an exception is thrown, the finallyblock will execute even if no catch statement matches
the exception.
The finally clause is optional. The finally block follows a try block or a catch block.
Syntax:
try
{
// Protected code
}
catch (ExceptionType1 e1)
{
// Catch block
}
finally
{
// The finally block always executes.
}
Example:
class AE
{
public static void main(String args[])
{
int d, a;
try // monitor a block of code.
{
d = 0;
a = 42 / d;
}
catch (ArithmeticException e) // catch divide-by-zero error
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("The finally statement is executed");
}
System.out.println("After catch statement.");
}
}
Checked and Unchecked Exceptions in Java, there are two types of exceptions in java: First is
predefined exceptions, and second user-defined exceptions.
The predefined exceptions are those exceptions that are already defined by the java system.
All the predefined exceptions are further divided into two groups:
1. Checked Exceptions
2. Unchecked Exceptions
Checked exceptions are those exceptions that are checked by the java compiler itself at
compilation time and are not under runtime exception class hierarchy. If a method throws a
checked exception in a program, the method must either handle the exception or pass it to a
caller method.
Checked exceptions must be handled either by using try and catch block or by using throws
clause in the method declaration. If not handles properly, it will give a compile-time error.
Most people have confusion and say that checked exceptions occur at compile-time, that is
wrong. All exceptions always occur at runtime only but some exceptions are detected at compile-
time and some other at runtime.
The exceptions that are checked by Java compiler at compilation time is called checked
exception in Java. All the exceptions except RuntimeException, Error, and their subclasses are
checked exceptions.
class test
for(int i=0;i<n;i++)
System.out.println(i);
Thread.sleep(1000);
}
}
class demo
try
m1.method(5);
catch(InterruptedException e)
System.out.println("exception occur");
Built-in Exceptions
Que:
1. List any four inbuilt exceptions.
2. List four different inbuilt exceptions of Java.
Ans:
Built-in exceptions are the exceptions which are available in Java libraries.
Following is the list of Java Checked Exceptions:
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.
1
ClassNotFoundException
Class not found.
2
CloneNotSupportedException
Attempt to clone an object that does not implement the Cloneable interface.
3
IllegalAccessException
Access to a class is denied.
4
InstantiationException
Attempt to create an object of an abstract class or 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.
User-Defined Exception
Java provides us facility to create our own exceptions which are basically derived classes
of Exception.
For example:
class ThrowExcep
{
static void div() throws MyException
{
int a=2,b=0;
if(b==0)
throw new MyException("demo");
else
{
int ar=a/b;
}
}
public static void main(String args[])
{
try
{
div();
}
catch(MyException e)
{
System.out.println("Divide");
}
}
}