Exception Handling
Exception Handling
• If we get an exception for file I/O then it is quite possible that the files
we are dealing with do not exist.
• At some other time, there may be errors like network issues, printer
not available or functioning, etc.
Exception
• In a program, apart from exceptions, we also get errors.
• Thus, to handle the exceptions effectively, we need to be aware of the
differences between error and an exception.
• An error indicates a more serious issue with the application and the
application should not attempt to catch it. On the contrary, the exception
is a condition that any reasonable application will try to catch.
• Thus an error in the application is more severe and the applications
would crash when they encounter an error. Exceptions on the other
hand occur in code and can be handled by the programmer by providing
corrective actions.
Exception
• What Is Exception Handling?
• The Exception Handling in Java is a mechanism using which the normal flow
of the application is maintained.
• To do this, we employ a powerful mechanism to handle runtime errors or
exceptions in a program.
• A sequence of code that is used to handle the exception is called the
“Exception handler”. An exception handler interrogates the context at the
point when the exception occurred.
• This means that it reads the variable values that were in scope while the
exception occurred and then restores the Java program to continue with
normal flow.
Exception
• Benefits Of Exception Handling:
• The major benefit of Exception handling is that it maintains the
normal flow of the application despite the occurrence of an
exception.
• When an exception occurs, the program usually terminates abruptly.
Exception
public Exception() A default constructor that constructs a new
exception with the message as null.
public Exception(String message,Throwable cause) Constructs a new exception using a given message
and cause.
public Exception(Throwable cause) Constructs a new exception with the given cause and
a message given by (cause==null ? null:
cause.toString()) (which typically contains the class
and detail message of cause).
protected Exception(String message, Throwable Constructs a new exception with the given message,
cause, boolean enableSuppression, boolean cause, suppression (enabled or disabled), and the
writableStackTrace) writable stack trace (enabled or disabled).
Exception
Method Prototype Description
public String getMessage() Get a detailed message about the exception that
occurred.
public String toString() Concatenates the name of the class with the result of
getMessage() and returns the resultant string.
public void printStackTrace() Prints the result of toString() and the contents of stack
trace to the error output stream, System.err.
public StackTraceElement [] getStackTrace() Get each element in the stack trace in the form of an
array.
public Throwable fillInStackTrace() Fill the stack trace with the current stack trace.
Exception
class Main
{
public static void main(String args[]){
//declare a String variable and initialize it to null
String myStr = null;
//print the string
System.out.println(myStr.length());
} //Here we provide a string variable initialized to a null value. When we try to print this variable,
an exception is thrown as the String value cannot be null.
}
Exception
1.Types of Exception:Checked Exception Unchecked Exception Error
• Some exceptions are checked at the compile-time when the code is compiled. These are
“Checked exceptions”. The Java program throws a compilation error when it finds that
the code inside a program is error-prone.
• We can take care of the compilation errors thrown by checked exception by handling the
exceptions by either enclosing the code in a try-catch block or using the throws keyword.
• In the Exception hierarchy, the class directly inheriting Throwable class like IOException,
ClassNotFoundException, etc. are all checked exception except for the classes
RuntimeException and Error. These are unchecked exceptions.
Exception
import java.io.*;
class Main {
public static void main(String args[])
{
FileInputStream fis = null;
//Open a file
fis = new FileInputStream("C:/myfile.txt");
int k;
• Answer: Exceptions are events that disrupt the normal flow of the
program.
• We can handle exceptions in our program and continue with the
program normally.
• An error is an irrecoverable event that cannot be handled and
terminates
• the program.
Questions
• Q #3) What do you mean by Exception Handling?
• Case 3: When exception rise and not handled by the catch block
• In this case, the program throws an exception but not handled by
catch so finally block execute after the try block and after the
execution of finally block program terminate abnormally, But finally
block execute fine.
Types of Exceptions
• #1) ArithmeticException: Arithmetic abnormalities like divide by zero
results in ArithmeticException.
• #2) ArrayIndexOutOfBoundsException:
ArrayIndexOutOfBoundsException is thrown when an array element is
accessed using an illegal index. The index used is either beyond the
size of the array or is negative.
• #3) ClassNotFoundException: If the class definition is not found then
the ClassNotFoundException is raised
• #4) FileNotFoundException: FileNotFoundException is given when the
file does not exist or does not open.
Types of Exceptions
• #5) IOException: IOException is thrown when the input-output
operation fails or is interrupted.
• #6) InterruptedException: Whenever a thread is doing processing or
sleeping or waiting, then it is interrupted by throwing
InterruptedException.
• #7) NoSuchFieldException: If a class does not contain a specified field
or variable, then it throws NoSuchFieldException.
• #8) NoSuchMethodException: When the method being accessed is
not found, then NoSuchMethodException is raised.
Types of Exceptions
• #9) NullPointerException: NullPointerException is raised when a null
object is referred. This is the most important and most common
exception in Java.
• #10) NumberFormatException: This exception is raised when a method
could not convert a string into a numeric format.
• #11) RuntimeException: Any exception that occurs at runtime is a
RuntimeException.
• #12) StringIndexOutOfBoundsException: The
StringIndexOutOfBoundsException is thrown by String class and
indicates that the index is beyond the size of the String object or is
negative.
Types of Exceptions
• #13) EOFException: EOFException is a part of the java.io package and
is thrown when the end of file is reached and the file is being read.
• #14) IllegalArgumentException: IllegalArgumentException is thrown
when illegal or invalid arguments are passed to the method. For
example, the wrong data format, null value when non-null is required
or out of range arguments.
• #15) InputMismatchException: InputMismatchException is thrown
when the input read does not match a pattern specified. For example,
if the program expects integer and reads a float, then the
InputMismatchException is raised.
Types of Exceptions
• #16) NoSuchElementException: NoSuchElementException is thrown
when the next element accessed does not exist.
• #17) ConcurrentModificationException:
ConcurrentModificationException is usually thrown by Collection
classes. This exception is thrown when the objects try to modify a
resource concurrently.
• So far we have discussed all the exceptions that are built-in or
provided by Java language. Apart from these exceptions, we can also
define our own exceptions. These are called Custom exceptions or
user-defined exceptions.
Throw keyword
• The throw keyword in Java is used to explicitly throw an exception from
a method or any block of code. We can throw either checked or
unchecked exception. The throw keyword is mainly used to throw
custom exceptions.
• throw Instance
• Example:
• throw new ArithmeticException("/ by zero");
• But this exception i.e, Instance must be of type Throwable or a subclass
of Throwable. For example Exception is a sub-class of Throwable and
user defined exceptions typically extend Exception class.
Throw keyword
• The flow of execution of the program stops immediately after the
throw statement is executed and the nearest enclosing try block is
checked to see if it has a catch statement that matches the type of
exception. If it finds a match, control is transferred to that statement
otherwise next enclosing try block is checked and so on. If no
matching catch is found then the default exception handler will halt
the program.
Throws keyword
• throws is a keyword in Java which is used in the
signature of method to indicate that this method might
throw one of the listed type exceptions. The caller to
these methods has to handle the exception using a try-
catch block.
• throws keyword is required only for checked exception
and usage of throws keyword for unchecked exception
is meaningless.
• throws keyword is required only to convince compiler
and usage of throws keyword does not prevent
abnormal termination of program.
• By the help of throws keyword we can provide