0% found this document useful (0 votes)
24 views65 pages

Exception Handling

The document provides an overview of exception handling in Java, detailing mechanisms for managing runtime exceptions to prevent abnormal program termination. It covers various types of exceptions, the Java exception class hierarchy, and keywords like try, catch, throw, throws, and finally. Additionally, it discusses user-defined exceptions, method overriding with exceptions, chained exceptions, and Java enumerations, including their definitions and usage.

Uploaded by

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

Exception Handling

The document provides an overview of exception handling in Java, detailing mechanisms for managing runtime exceptions to prevent abnormal program termination. It covers various types of exceptions, the Java exception class hierarchy, and keywords like try, catch, throw, throws, and finally. Additionally, it discusses user-defined exceptions, method overriding with exceptions, chained exceptions, and Java enumerations, including their definitions and usage.

Uploaded by

Jyothi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 65

Exception Handling

Exception Handling

• Exception Handling is a mechanism to handle exception at


runtime. Exception is a condition that occurs during program
execution and lead to program termination abnormally. There
can be several reasons that can lead to exceptions, including
programmer error, hardware failures, files that need to be
opened cannot be found, resource exhaustion etc.
• To handle this problem, we use exception handling that avoid
program termination and continue the execution by skipping
exception code.
• Java exception handling provides a meaningful message to the
user about the issue rather than a system generated message,
which may not be understandable to a user.
Uncaught Exceptions

class UncaughtException
{
public static void main(String args[])
{
int a = 0;
int b = 7/a; // Divide by zero, will lead to exception
}
}
Java Exception

• A Java Exception is an object that describes the


exception that occurs in a program. When an
exceptional events occurs in java, an exception is said
to be thrown. The code that's responsible for doing
something about the exception is called an exception
handler
How to Handle Exception

• Java provides controls to handle exception in the


program. These controls are listed below.
• Try : It is used to enclose the suspected code.
• Catch: It acts as exception handler.
• Finally: It is used to execute necessary code.
• Throw: It throws the exception explicitly.
• Throws: It informs for the possible exception.
Types of Exceptions
• Checked Exception
• The exception that can be predicted by the JVM at the compile time
for example : File that need to be opened is not found, SQLException
etc. These type of exceptions must be checked at compile time.
• Unchecked Exception
• Unchecked exceptions are the class that extends RuntimeException
class. Unchecked exception are ignored at compile time and checked
at runtime. For example : ArithmeticException, NullPointerException,
Array Index out of Bound exception. Unchecked exceptions are
checked at runtime.
• Error
• Errors are typically ignored in code because you can rarely do
anything about an error. For example, if stack overflow occurs, an
error will arise. This type of error cannot be handled in the code.
Java Exception class Hierarchy

• All exception types are subclasses of class Throwable,


which is at the top of exception class hierarchy.
• Exception class is for exceptional conditions that
program should catch. This class is extended to create
user specific exception classes.
• RuntimeException is a subclass of Exception.
Exceptions under this class are automatically defined
for programs.
• 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.
try and catch in Java
• Try and catch both are Java keywords and used
for exception handling. The try block is used to
enclose the suspected code. Suspected code is a code
that may raise an exception during program execution.
• The catch block also known as handler is used to
handle the exception. It handles the exception thrown
by the code enclosed into the try block. Try block must
provide a catch handler or a finally block. We will
discuss about finally block in our next tutorials.
• The catch block must be used after the try block only.
We can also use multiple catch block with a single try
block.
Syntax

try{
// suspected code
}catch(ExceptionClass ec){}
Multiple catch blocks

• A try block can be followed by multiple catch blocks. It


means we can have any number of catch blocks after a
single try block. If an exception occurs in the guarded
code(try block) the exception is passed to the first catch
block in the list. If the exception type matches with the
first catch block it gets caught, if not the exception is
passed down to the next catch block. This continue until
the exception is caught or falls through all catches.
try
{
// suspected code
}
catch(Exception1 e)
{
// handler code
}
catch(Exception2 e)
{
// handler code
}
Example for Unreachable Catch
block
Nested try statement

• try statement can be nested inside another block


of try. Nested try block is used when a part of a block
may cause one error while entire block may cause
another error. In case if inner try block does not have
a catch handler for a particular exception then the
outer try catch block is checked for match.
Note
1.If you do not explicitly use the try catch blocks in your program,
java will provide a default exception handler, which will print the
exception details on the terminal, whenever exception occurs.
2.Super class Throwable overrides toString() function, to display
error message in form of string.
3.While using multiple catch block, always make sure that sub-
classes of Exception class comes before any of their super
classes. Else you will get compile time error.
4.In nested try catch, the inner try block uses its own catch block as
well as catch block of the outer try, if required.
5.Only the object of Throwable class or its subclasses can be
thrown.
Java try with Resource Statement
• Try with resource is a new feature of Java that was
introduced in Java 7 and further improved in Java 9. This
feature add another way to exception handling with
resources management. It is also referred as automatic
resource management. It close resources
automatically by using AutoCloseable interface..
• Resource can be any like: file, connection etc and we
don't need to explicitly close these, JVM will do this
automatically.
Try with Resource Syntax
try(resource-specification(there can be more than one resource))
{
//use the resource
}
catch()
{
// handler code
}
Any object that implements java.lang.AutoCloseable or java.io.Closeable, can be passed
as a parameter to try statement. A resource is an object that is used in program and
must be closed after the program is finished. The try-with-resources statement ensures
that each resource is closed at the end of the statement of the try block. We do not have
to explicitly close the resources.
• In Java 7, try-with-resource was introduced and in which
resource was created inside the try block. It was the
limitation with Java 7 that a connection object created
outside can not be refer inside the try-with-resource.
• In Java 9 this limitation was removed so that now we
can create object outside the try-with-resource and then
refer inside it without getting any error.
Java throw, throws and finally
Keyword
• Throw, throws and finally are the keywords in Java that are used in
exception handling. The throw keyword is used to throw an exception
and throws is used to declare the list of possible exceptions with the
method signature. Whereas finally block is used to execute essential
code, specially to release the occupied resources.
Java Throw

• The throw keyword is used to throw an exception


explicitly. Only object of Throwable class or its sub
classes can be thrown. Program execution stops on
encountering throw statement, and the closest catch
statement is checked for matching type of exception.
Syntax
throw ThrowableInstance
Creating Instance of Throwable class
new NullPointerException("test");
Java throws Keyword
• The throws keyword is used to declare the list of exception
that a method may throw during execution of program. Any
method that is capable of causing exceptions must list all the
exceptions possible during its execution, so that anyone
calling that method gets a prior knowledge about which
exceptions are to be handled. A method can do so by using
the throws keyword.
• type method_name(parameter_list) throws exception_list
•{
• // definition of method
•}
throw throws
throw keyword is used to throw an exception throws keyword is used to declare an exception
explicitly. possible during its execution.
throw keyword is followed by an instance of throws keyword is followed by one or more Exception
Throwable class or one of its sub-classes. class names separated by commas.
throws keyword is used with method signature
throw keyword is declared inside a method body.
(method declaration).
We cannot throw multiple exceptions using throw We can declare multiple exceptions (separated by
keyword. commas) using throws keyword.
finally clause
• A finally keyword is used to create a block of code that
follows a try block. A finally block of code is always
executed whether an exception has occurred or not.
Using a finally block, it lets you run any cleanup type
statements that you want to execute, no matter what
happens in the protected code. A finally block appears
at the end of catch block.
User defined Exception subclass in
Java
• Java provides rich set of built-in exception classes like: ArithmeticException,
IOException, NullPointerException etc. all are available in the java.lang
package and used in exception handling. These exceptions are already set to
trigger on pre-defined conditions such as when you divide a number by zero it
triggers ArithmeticException.
• Java allows us to create our own exception class to provide own exception
implementation. These type of exceptions are called user-defined exceptions
or custom exceptions.
• You can create your own exception simply by extending java Exception class.
You can define a constructor for your Exception (not compulsory) and you can
override the toString() function to display your customized message on catch.
Custom Exception
1.Extend the Exception class to create your own
exception class.
2.You don't have to implement anything inside it, no
methods are required.
3.You can have a Constructor if you want.
4.You can override the toString() function, to display
customized message.
Java Method Overriding with Exception Handling

• There are few things to remember when overriding a


method with exception handling because method of
super class may have exception declared. In this
scenario, there can be possible two cases: either
method of super class can declare exception or not.
• If super class method declared exception then the
method of sub class may declare same exception class,
sub exception class or no exception but can not parent
of exception class.
Method overriding in Subclass with Checked Exception
Checked exception is the exception which is expected or known to occur at compile time hence they
must be handled at compile time.
Method overriding in Subclass with UnChecked Exception
Unchecked Exceptions are the exception which extend the class RuntimeExeption and are thrown as
a result of some runtime error.
• If Super class method throws an exception, then
Subclass overriden method can throw the same
exception or no exception, but must not throw parent
exception of the exception thrown by Super class
method.
• It means, if Super class method throws object
of NullPointerException class, then Subclass method
can either throw same exception, or can throw no
exception, but it can never throw object
of Exception class (parent of NullPointerException
class).
Chained Exception in Java
• Chained Exception was added to Java in JDK 1.4. This feature
allows you to relate one exception with another exception, i.e
one exception describes cause of another exception. For
example, consider a situation in which a method throws
an ArithmeticException because of an attempt to divide by
zero but the actual cause of exception was an I/O error which
caused the divisor to be zero. The method will throw
only ArithmeticException to the caller. So the caller would
not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
• Two new constructors and two new methods were added
to Throwable class to support chained exception.
1.Throwable(Throwable cause)
2.Throwable(String str, Throwable cause)
• In the first constructor, the paramter cause specifies the
• getCause() and initCause() are the two methods
added to Throwable class.
• getCause() method returns the actual cause
associated with current exception.
• initCause() set an underlying cause(exception) with
invoking exception.
Exception propagation

• In Java, an exception is thrown from the top of the


stack, if the exception is not caught it is put in the
bottom of the stack, this process continues until it
reaches to the bottom of the stack and caught. It is
known as exception propagation. By default, an
unchecked exception is forwarded in the called chain.
Java Enumerations

• Enumerations was added to Java language in


JDK5. Enumeration means a list of named constant. In
Java, enumeration defines a class type. An Enumeration
can have constructors, methods and instance variables.
It is created using enum keyword. Each enumeration
constant is public, static and final by default. Even
though enumeration defines a class type and have
constructors, you do not instantiate
an enum using new. Enumeration variables are used
and declared in much a same way as you do a primitive
variable.
How to Define and Use an Enumeration

//Enumeration defined
enum Subject
{
Java, Cpp, C, Dbms
}
Identifiers Java, Cpp, C and Dbms are
called enumeration constants. These are public, static
and final by default.
Values() and ValueOf() method

• All the enumerations predefined methods values() and valueOf().


values() method returns an array of enum-type containing all the
enumeration constants in it.
• Syntax
• public static enum-type[ ] values()
• valueOf() method is used to return the enumeration constant whose
value is equal to the string passed in as argument while calling this
method.
public static enum-type valueOf (String str)
1.Enumerations are of class type, and have all the
capabilities that a Java class has.
2.Enumerations can have Constructors, instance
Variables, methods and can even implement Interfaces.
3.Enumerations are not instantiated using new keyword.
4.All Enumerations by default
inherit java.lang.Enum class.

You might also like