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

Exception Handling

Uploaded by

muditjha608
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Exception Handling

Uploaded by

muditjha608
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

Exception Handling

Try Catch Finally Throw Throws


Exception
• When we are executing Java programs, the normal behavior or
normal flow of the program is interrupted, due to some unexpected
events.
• For example, we open a file for reading the data.
• When the Open file call is executed, we find the file we are trying to
open is missing. This results in the interruption of the normal flow of
the program.
Exception
• This event that affects or interrupts the normal flow of the program is
called the “Exception”.
• When an exception occurs in the program, the program execution is
terminated.
• As this is an abrupt termination, the system generates a message and
displays it.
• The message generated by the system may be cryptic like some codes
or unreadable.
Exception
• Thus the normal user should understand why the program stopped its
execution abruptly, he/she should know the reason. The system
generated messages as a result of exception may not be helpful. In
Java, we can handle the exception and provide meaningful messages
to the user about the issue.
• This handling of exception, commonly known as “Exception handling”
is one of the salient features of Java programming.
Exception
• Reasons For The Exception To Occur:
• We can have various reasons due to which exceptions can occur.
• If its an exception related to input, then the reason may be that the
input data is incorrect or unreadable.

• 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.

• Having an exception handler in a program will not cause the program


to terminate abruptly. Instead, an exception handler makes sure that
all the statements in the program are executed normally and the
program flow doesn’t break abruptly.
Exception
• Exception Hierarchy In Java:
• The below diagram shows the Exception hierarchy in Java.
• The class java.lang.Throwable (descendent of Object class) is the root
class of Java Exception. The classes Exception and Error are derived
from this class.
• Exception class is the base class for all the other exceptions.
Exception
Exception
• Exception Class In Java
• As seen in the hierarchy diagram, class Throwable has two direct
subclasses i.e. Exception and Error. Exceptions arising from an
external source are described in the Exception class.

• The Exception class declares the constructors as the same as


Throwable class and invoking of each constructor also invokes its
Throwable counterpart. Exception class does not declare its methods,
it inherits Throwable class methods.
Constructor Description

Exception
public Exception() A default constructor that constructs a new
exception with the message as null.

public Exception(String message) Constructor to construct a new exception with the


given message. In this case, the cause is not
initialized, and a subsequent call to
Throwable.initCause (java.lang.Throwable) may be
used to initialize the cause.

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 Throwable getCause() Get the cause of the exception represented by a


throwable object

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;

//read contents of the file


while(( k = fis.read() ) != -1)
{
System.out.print((char)k);
}

//close the file


fis.close();
}
}
Exception
Exception
• The following Java program demonstrates the Checked
Exceptions, FileNotFoundException, and IOException. In
this program, we try to open a non-existing file and read
from it.
• As the file does not exist, the open file method throws
FileNotFoundException. Next, when we try to read the
contents of the file and close the file, the methods calls
throw IOException.
Exception
• Unchecked exceptions are the exceptions that are
checked at run time. Hence despite exceptions, a
compilation of programs will be successful. Most of the
unchecked exceptions are thrown owing to the bad data
used in the program.
• The classes that inherit “RuntimeException” are
unchecked exceptions. Exceptions like
ArrayIndexOutofBounds Exception, ArithmeticException,
NullPOinterException, etc. are examples of unchecked
exceptions.
Exception
• class UnchekE {
• public static void main(String args[])
• {
• int num1=10;
• int num2=0;
• //divide both numbers and print the result
• int result=num1/num2;
• System.out.println(result);
• }
•}
Exception

We see that the program is compiled successfully and then the


ArithmeticException is thrown at runtime.
Exception
• Examples of Unchecked Exception:
• ArrayIndexOutOfBoundsException
• NullPointerException
• IllegalArgumentException
• NumberFormatException
Exception
• class Main {
• public static void main(String args[])
• {
• try {
• //define two numbers
• int num1 = 100, num2 = 0;
• int result = num1 / num2; // divide by zero
• //print the result
• System.out.println("Result = " + result);
• }
• catch (ArithmeticException e) {
• System.out.println("ArithmeticException:Division by Zero");
• }
• }
• }// output:
Try We specify the block of code that might give rise to
the exception in a special block with a “Try” keyword.

Catch When the exception is raised it needs to be caught by


the program. This is done using a “catch” keyword. So
a catch block follows the try block that raises an
exception. The keyword catch should always be used
with a try.

Finally Sometimes we have an important code in our program


that needs to be executed irrespective of whether or
not the exception is thrown. This code is placed in a
special block starting with the “Finally” keyword. The
Finally block follows the Try-catch block.

Throw The keyword “throw” is used to throw the exception


explicitly.
Throws The keyword “Throws” does not throw an exception
but is used to declare exceptions. This keyword is used
to indicate that an exception might occur in the
program or method.
Questions
• Q #1) What do you mean by exception?

• Answer: An event that occurs during the execution of a program and


• disrupts the normal execution flow of the program is called Exception.
• The exception is unwanted & unexpected and may occur owing to
external
• factors or programming errors.
Questions
• Q #2) What is the difference between Error and Exception?

• 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?

• Answer: The process of specifying the sequence of steps in a program


• to handle the exception is called Exception Handling.
• By providing exception handlers in a program,
• we can ensure the normal flow of the program.
Questions
• Q #4) What are the advantages of Exception Handling in Java?

• Answer: Using exception handling we can maintain the normal flow of


• execution of an application. We can also propagate the errors up the
• call stack when we provide exception handlers.
Questions
• Q #5) What is the use of Exception Handling?

• Answer: Not terminating the normal flow of execution of an application


• is the major use of having exception handlers in a program.
• Without exception handlers, the program will terminate and the normal
• execution flow will be interrupted when an exception occurs.

• With exception properly handled in the program, it can continue with


• its normal execution even when an exception occurs.
Questions
• public class TestT{
• public static void main(String args[]){
• //test
• //\u000d System.out.println("hi");
•}
•}
Questions
• public class TestT1{
• public static void main(String args[]){
• //test
• // System.out.println("hi");
• String s="one"+1+2+"two"+"three"+3+4+"four"+"five"+5;
• System.out.println(s);
•}
•}
Questions
• public class TestT2{
• public static void main(String args[]){
• //test
• // System.out.println("hi");
• //String s="one"+1+2+"two"+"three"+3+4+"four"+"five"+5;
• int i=10+ +11- -12+ +13- -14+ +15;
• System.out.println(i);
•}
•}
Ugly.java
• \u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020\u0020
• \u0063\u006c\u0061\u0073\u0073\u0020\u0055\u0067\u006c\u0079
• \u007b\u0070\u0075\u0062\u006c\u0069\u0063\u0020\u0020\u0020
• \u0020\u0020\u0020\u0020\u0073\u0074\u0061\u0074\u0069\u0063
• \u0076\u006f\u0069\u0064\u0020\u006d\u0061\u0069\u006e\u0028
• \u0053\u0074\u0072\u0069\u006e\u0067\u005b\u005d\u0020\u0020
• \u0020\u0020\u0020\u0020\u0061\u0072\u0067\u0073\u0029\u007b
• \u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074
• \u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0020
• \u0022\u0048\u0065\u006c\u006c\u006f\u0020\u0077\u0022\u002b
• \u0022\u006f\u0072\u006c\u0064\u0022\u0029\u003b\u007d\u007d
Exception Handling
• Try, catch and finally block:
• An exception is handled by try, catch block.
• Statements which can lead to exceptions are written inside the try block.
• When an exception occurs, the statements inside the catch block will be
executed. If an exception does not occur, the catch block will not be
executed.
• Irrespective of exception occurred or not occurred, the finally block will
be executed.
• “Throw” keyword is used to throw the exception, whereas the “throws
“keyword is used to declare the exception.
Exception Handling
• The finally block in java is used to put important codes such as clean
up code e.g. closing the file or closing the connection. The finally
block executes whether exception rise or not and whether exception
handled or not. A finally contains all the crucial statements regardless
of the exception occurs or not.

• Case 1: When an exception does not rise


• In this case, the program runs fine without throwing any exception
and finally block execute after the try block.
Exception Handling
• Case 2: When the exception rises and handled by the catch block
• In this case, the program throws an exception but handled by the
catch block, and finally block executes after the catch block.

• 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

You might also like