SlideShare a Scribd company logo
Exception Handling in Java
What is an Exception in Java?
• An exception is an unwanted or unexpected event that occurs
during the execution of the program, that disrupts the flow of
the program.
• For example, if a user is trying to divide an integer by 0 then it
is an exception, as it is not possible mathematically.
• There are various types of interruptions while executing any
program like errors, exceptions, and bugs. These interruptions
can be due to programming mistakes or due to system issues.
Depending on the conditions they can be classified as errors
and exceptions.
• Java has classes that are used to handle built-in exceptions and
provision to create user-defined exceptions.
1. Exception
• Exceptions are unwanted conditions that disrupt the
flow of the program.
• Exceptions usually occur due to the code and can be
recovered.
• Exceptions can be of both checked(exceptions that are
checked by the compiler) and unchecked(exceptions
that cannot be checked by the compiler) type.
• They can occur at both run time and compile time.
• In Java, exceptions belong to java.lang.Exception class.
2. Error
• An error is also an unwanted condition but it is
caused due to lack of resources and indicates a
serious problem.
• Errors are irrecoverable, they cannot be handled
by the programmers.
• Errors are of unchecked type only.
• They can occur only at run time.
• In java, errors belong to java.lang.error class.
• Eg: OutOfMemmoryError.
What is Exception Handling in java?
• Exception handling in java is a mechanism to handle
unwanted interruptions like exceptions and
continue with the normal flow of the program.
• Java uses try-catch blocks and other keywords like
finally, throw, and throws to handle exceptions.
• JVM(Java Virtual Machine) by default handles
exceptions, when an exception is raised it will halt
the execution of the program and throw the
occurred exception.
Why Handle Java Exception?
• We handle exceptions in java to make sure the program
executes properly without any halt, which occurs when an
exception is raised.
• These exceptions are runtime as well as compile-time.
• They may be minor exceptions but can cause a problem in
executions of the program, hence it becomes necessary to
handle java exceptions. If java exceptions are not handled,
programs may crash and execution is halted in between.
• For example, if there is a program with some lines of code and
an exception occurs a mid-way after executing certain lines of
code, in this case, the execution terminates abruptly.
• But if the programmer handles the exceptions explicitly, all the
statements of code are executed properly and the flow of the
program is maintained.
Example program
• class SampleCode
• {
• public static void main(String args[])
• {
• Sysytem.out.println("Hello World!");
• int a = 10;
• int b = 0;
• System.out.println(a / b);
• System.out.println("Welcome to java programming.");
• System.out.println("Bye.")
• }
• }
Output
• Hello World!
• Exception in thread "main" java.lang.ArithmeticException: / by zero
• at SampleException.main(SampleException.java:8)
• In the above code, the first three lines in the main method
are executed properly.
• At the 4th line, an integer is divided by 0, which is not
possible and an exception is raised by JVM(Java Virtual
Machine).
• In this case, the exception is not handled by the
programmer which will halt the program in between by
throwing the exception, and the rest of the lines of code
won't be executed.
How does JVM handles an Exception?
• Java exceptions raised during the program execution are nothing but objects of
the respective exception class in the hierarchy shown above.
• The exceptions have a naming and inheritance hierarchy to the main exception
class in java i.e. Throwable class.
• All java exception objects support the toString() method, which returns the full
name of the exception class as an output to the command prompt, which helps
to understand the exceptional condition.
• Whenever an exception has occurred inside a method, the method creates an
exception object and hands it over to JVM.
• This object contains the name and description of the exception and the current
state of the program where the exception has occurred.
• This is called the process of object creation and handing it over to JVM is known
as throwing an Exception.
• This object is an exception that is further handled by JVM.
How does JVM handles an Exception?
• When an exception is raised there is an ordered list of
the methods that had been called by JVM to get the
method where the exception has occurred this list is
called Call Stack.
• JVM searches through this call stack to get the proper
code to handle the occurred exception, this code
block is known as an Exception handler.
• When an appropriate handler is found JVM handles
the exception according to the code in the handler
and shows the state of the program.
Major reasons why an exception Occurs
• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Out of bound
• Null reference
• Type mismatch
• Opening an unavailable file
• Database errors
• Arithmetic errors
Hierarchy of Java Exception Classes
• As java is an object-oriented language every
class extends the Object class. All exceptions
and errors are subclasses of class Throwable.
• Throwable is the base/superclass of exception
handling hierarchy in java. This class is further
extended in different classes like exception,
error, and so on.
Exception Hierarchy
• All exception and error types are subclasses of the
class Throwable, which is the base class of the hierarchy.
• One branch is headed by Exception. This class is used for
exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception.
• Another branch, Error is used by the Java run-time
system(JVM) to indicate errors having to do with the
run-time environment itself(JRE). StackOverflowError is
an example of such an error.
Hierarchy of Java Exception Classes
Exception Hierarchy
Types of Exceptions
• Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
Types of Exceptions Handling in Java
• 1. Checked Exceptions
• Checked exceptions are those exceptions that are
checked at compile time by the compiler.
• The program will not compile if they are not handled.
• These exceptions are child classes of the Exception
class.
• IOException, ClassNotFoundException,
InvocationTargetException, and SQL Exception are a
few of the checked exceptions in Java.
Types of Exceptions Handling in Java
• 2. Unchecked Exceptions
• Unchecked exceptions are those exceptions that are
checked at run time by JVM, as the compiler cannot
check unchecked exceptions,
• The programs with unchecked exceptions get compiled
successfully but they give runtime errors if not handled.
• These are child classes of Runtime Exception Class.
• ArithmeticException, NullPointerException,
NumberFormatException, IndexOutOfBoundException
are a few of the unchecked exceptions in Java.
How does a Programmer Handles an
Exception?
• Customized exception handling in java is achieved using
five keywords: try, catch, throw, throws, and finally. Here
is how these keywords work in short.
• Try block contains the program statements that may
raise an exception.
• Catch block catches the raised exception and handles it.
• Throw keyword is used to explicitly throw an exception.
• Throws keyword is used to declare an exception.
• Finally block contains statements that must be executed
after the try block.
Example of Exception Handling in Java
• class ExceptionExample {
• public static void main(String args[]) {
• try {
• // Code that can raise exception
• int div = 509 / 0;
• } catch (ArithmeticException e) {
• System.out.println(e);
• }
• System.out.println("End of code");
• }
• }
• Output:
• java.lang.ArithmeticException: / by zero
• End of code
1. try block
• try block is used to execute doubtful statements which can throw exceptions.
• try block can have multiple statements.
• Try block cannot be executed on itself, there has to be at least one catch block
or finally block with a try block.
• When any exception occurs in a try block, the appropriate exception object
will be redirected to the catch block, this catch block will handle the
exception according to statements in it and continue the further execution.
• The control of execution goes from the try block to the catch block once an
exception occurs.
• Syntax
• try {
• //Doubtfull Statements.
• }
2. catch block
• catch block is used to give a solution or alternative for an exception.
• catch block is used to handle the exception by declaring the type of
exception within the parameter.
• The declared exception must be the parent class exception or the generated
exception type in the exception class hierarchy or a user-defined exception.
• You can use multiple catch blocks with a single try block.
• Syntax
• try {
• //Doubtful Statements
• }
• catch(Exception e)
• {
• }
1. try-catch block
• public class Main {
• public static void main(String[ ] args) {
• try {
• int[] myNumbers = {10, 1, 2, 3, 5, 11};
• System.out.println(myNumbers[10]);
• } catch (Exception e) {
• System.out.println("Something went wrong.");
• }
• }
• }
• Output:
• Something went wrong.
• In this program, the user has declared an array
myNumbers in the try block, which has some
numbers stored in it. And the user is trying to access
an element of the array that is stored at the 10th
position.
• But array has only 6 elements and the highest
address position is 5. By doing this user is trying to
access an element that is not present in the array,
this will raise an exception, and the catch block will
get executed.
2. Multiple Catch Blocks
• Java can have a single try block and multiple
catch blocks and a relevant catch block gets
executed.
• Example 1:
• Here we are giving doubtful statements in a
try block and using multiple catch blocks to
handle the exception that will occur according
to the statement.
• public class MultipleCatchBlock1 {
• public static void main(String[] args) {
• try {
• int a[] = new int[5];
• a[5] = 30 / 0;
• } catch (ArithmeticException e) {
• System.out.println("Arithmetic Exception occurs");
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("ArrayIndexOutOfBounds Exception occurs");
• } catch (Exception e) {
• System.out.println("Parent Exception occurs");
• }
• System.out.println("End of the code");
• }
• }
• Output:
• Arithmetic Exception occurs
• End of the code
• In this example, the try block has doubtful statements that
are trying to divide an integer by 0 and 3 catch blocks which
have mentioned the exceptions that can handle.
• After execution of the try block, the Arithmetic Exception is
raised and JVM starts to search for the catch block to handle
the same.
• JVM will find the first catch block that can handle the raised
exception, and control will be passed to that catch block.
• After the exception is handled the flow of the program
comes out from try-catch block and it will execute the rest
of the code.
• public class MultipleCatchBlock2 {
• public static void main(String[] args) {
• try {
• int a[] = new int[5];
• System.out.println(a[10]);
• } catch (ArithmeticException e) {
• System.out.println("Arithmetic Exception occurs");
• } catch (ArrayIndexOutOfBoundsException e) {
• System.out.println("ArrayIndexOutOfBounds Exception occurs");
• } catch (Exception e) {
• System.out.println("Parent Exception occurs");
• }
• System.out.println("rest of the code");
• }
• }
• Output:
• ArrayIndexOutOfBounds Exception occurs
• rest of the code
• In this example, try block has doubtful statements that are trying
to access elements that are not present in an array and 3 catch
blocks that have mentioned the exceptions that can handle.
• After execution of try block, ArrayIndexOutOfBounds Exception is
raised and JVM starts to search for the catch block to handle the
same.
• JVM will find the second catch block that can handle the raised
exception, and control will be passed to that catch block.
• After the exception is handled the flow of the program comes
out from try-catch block and it will execute rest of the code.
3. Nested Try Catch
• class NestingDemo {
• public static void main(String args[]) {
• //main try-block
• try {
• //try-block2
• try {
• //try-block3
• try {
• int arr[] = {
• 1,
• 2,
• 3,
• 4
• };
• /* I'm trying to display the value of
• * an element which doesn't exist. The
• * code should throw an exception
• */
• System.out.println(arr[10]);
• } catch (ArithmeticException e) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in try-block3");
• }
• } catch (ArithmeticException e) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in try-block2");
• }
• } catch (ArithmeticException e3) {
• System.out.print("Arithmetic Exception");
• System.out.println(" handled in main try-block");
• } catch (ArrayIndexOutOfBoundsException e4) {
• System.out.print("ArrayIndexOutOfBoundsException");
• System.out.println(" handled in main try-block");
• } catch (Exception e5) {
• System.out.print("Exception");
• System.out.println(" handled in main try-block");
• }
• }
• }
• Output:
• ArrayIndexOutOfBoundsException handled in main try-block
3. Nested Try Catch
• As you can see that the ArrayIndexOutOfBoundsException
occurred in the grandchild try-block3.
• Since try-block3 is not handling this exception, the control
then gets transferred to the parent try-block2 and looked for
the catch handlers in try-block2.
• Since the try-block2 is also not handling that exception, the
control gets transferred to the main (grandparent) try-block
where it found the appropriate catch block for an exception.
• We can use the finally block after the main try-catch block if
required.
4. finally block
• finally block is associated with a try, catch block.
• It is executed every time irrespective of
exception is thrown or not.
• finally block is used to execute important
statements such as closing statement, release
the resources, and release memory also.
• finally block can be used with try block with or
without catch block.
Syntax
• try
• {
• //Doubtful Statements
• }
• catch(Exception e)
• {
•
• }
• finally
• {
• //Close resources
• }
Example:
• public class Main {
• public static void main(String[] args) {
• try {
• int data = 100/0;
• System.out.println(data);
• } catch (Exception e) {
• System.out.println("Can't divide integer by 0!");
• } finally {
• System.out.println("The 'try catch' is finished.");
• }
• }
• }
• Output:
• Can't divide integer by 0!
• The 'try catch' is finished.
• Here, after the execution of try and catch blocks, finally block gets executed. finally block gets
executed even if the catch block is not executed.
throw
• 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.
• Syntax in Java throw
• throw Instance
• Example:
• throw new ArithmeticException("/ by zero");
• But this exception i.e., Instance must be of type Throwable or a
subclass of Throwable.
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, controlled 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.
Throw Keyword
• // Java program that demonstrates the use of throw
• class ThrowExcep {
• static void fun()
• {
• try {
• throw new NullPointerException("demo");
• }
• catch (NullPointerException e) {
• System.out.println("Caught inside fun().");
• throw e; // rethrowing the exception
• }
• }
• public static void main(String args[])
• {
• try {
• fun();
• }
• catch (NullPointerException e) {
• System.out.println("Caught in main.");
• }
• }
• }
• Output
• Caught inside fun().
• Caught in main.
Throw Keyword
• // Java program that demonstrates
• // the use of throw
• class Test {
• public static void main(String[] args)
• {
• System.out.println(1 / 0);
• }
• }
• Output
• Exception in thread "main" java.lang.ArithmeticException: / by zero
Java throws
• throws is a keyword in Java that is used in the
signature of a 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.
• Syntax of Java throws
• type method_name(parameters) throws
exception_list exception_list is a comma separated
list of all the exceptions which a method might
throw.
Java throws
• In a program, if there is a chance of raising an exception then
the compiler always warns us about it and compulsorily we
should handle that checked exception, Otherwise, we will get
compile time error saying unreported exception XXX must be
caught or declared to be thrown. To prevent this compile time
error we can handle the exception in two ways:
• By using try catch
• By using the throws keyword
• We can use the throws keyword to delegate the responsibility
of exception handling to the caller (It may be a method or JVM)
then the caller method is responsible to handle that exception.
Java throws Examples
• // Java program to illustrate error in case
• // of unhandled exception
• class tst {
• public static void main(String[] args)
• {
• Thread.sleep(10000);
• System.out.println("Hello Students");
• }
• }
• Output
• error: unreported exception InterruptedException; must be caught or declared to be
thrown
• Explanation
• In the above program, we are getting compile time error because there is a chance of
exception if the main thread is going to sleep, other threads get the chance to
execute the main() method which will cause InterruptedException.
Java throws Examples
• // Java program to illustrate throws
• class tst {
• public static void main(String[] args)
• throws InterruptedException
• {
• Thread.sleep(10000);
• System.out.println("Hello Students");
• }
• }
• Output
• Hello Students
• Explanation
• In the above program, by using the throws keyword we handled the InterruptedException and
we will get the output as Hello Geeks
Java throws Examples
• // Java program to demonstrate working of throws
• class ThrowsExecp {
• static void fun() throws IllegalAccessException
• {
• System.out.println("Inside fun(). ");
• throw new IllegalAccessException("demo");
• }
• public static void main(String args[])
• {
• try {
• fun();
• }
• catch (IllegalAccessException e) {
• System.out.println("caught in main.");
• }
• }
• }
• Output
• Inside fun(). caught in main.
Java throws Keyword
• throws keyword is required only for checked
exceptions and usage of the throws keyword for
unchecked exceptions is meaningless.
• throws keyword is required only to convince the
compiler and usage of the throws keyword does not
prevent abnormal termination of the program.
• With the help of the throws keyword, we can
provide information to the caller of the method
about the exception.
Java Custom Exception
• In Java, we can create our own exceptions that
are derived classes of the Exception class.
Creating our own Exception is known as
custom exception or user-defined exception.
• Basically, Java custom exceptions are used to
customize the exception according to user
need.
Java Custom Exception
• Consider the example 1 in which
InvalidAgeException class extends the
Exception class.
• Using the custom exception, we can have your
own exception and message. Here, we have
passed a string to the constructor of superclass
i.e. Exception class that can be obtained using
getMessage() method on the object we have
created.
Java Custom Exception
• Following are few of the reasons to use custom
exceptions:
• To catch and provide specific treatment to a subset of
existing Java exceptions.
• Business logic exceptions: These are the exceptions
related to business logic and workflow. It is useful for
the application users or the developers to understand
the exact problem.
• In order to create custom exception, we need to extend
Exception class that belongs to java.lang package.
Example
• Consider the following example, where we create a
custom exception named WrongFileNameException:
• public class WrongFileNameException extends Exception
• {
• public WrongFileNameException(String errorMessage)
• {
• super(errorMessage);
• }
• }
Ad

More Related Content

Similar to using Java Exception Handling in Java.pptx (20)

Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
sonalipatil225940
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Javasession4
Javasession4Javasession4
Javasession4
Rajeev Kumar
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
thenmozhip8
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
EXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograamingEXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograaming
MuskanNazeer
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
Ravindra Rathore
 
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
anuraggautam9792
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
Vadym Lotar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
sonalipatil225940
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2exception-handling-in-java.ppt unit 2
exception-handling-in-java.ppt unit 2
thenmozhip8
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
EXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograamingEXCEPTION HANDLING in prograaming
EXCEPTION HANDLING in prograaming
MuskanNazeer
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
exception-handling-in-java.ppt edfrgthyujki8ol9k8ij7uhygtrfdewd3r4tf5ghy67u8u...
anuraggautam9792
 

More from AshokRachapalli1 (20)

DATA MODEL Power point presentation for dbms
DATA MODEL Power point presentation for dbmsDATA MODEL Power point presentation for dbms
DATA MODEL Power point presentation for dbms
AshokRachapalli1
 
WEEK-2 DML and operators power point presentation
WEEK-2 DML and operators power point presentationWEEK-2 DML and operators power point presentation
WEEK-2 DML and operators power point presentation
AshokRachapalli1
 
Relational Algebra in DBMS 2025 power point
Relational Algebra in DBMS 2025 power pointRelational Algebra in DBMS 2025 power point
Relational Algebra in DBMS 2025 power point
AshokRachapalli1
 
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
CLOSURE OF AN ATTRIBUTE powerpontpresentatioCLOSURE OF AN ATTRIBUTE powerpontpresentatio
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
AshokRachapalli1
 
Relational algebra in database management system
Relational algebra in database management systemRelational algebra in database management system
Relational algebra in database management system
AshokRachapalli1
 
DBMS-3.1 Normalization upto boyscodd normal form
DBMS-3.1 Normalization upto boyscodd normal formDBMS-3.1 Normalization upto boyscodd normal form
DBMS-3.1 Normalization upto boyscodd normal form
AshokRachapalli1
 
Data base Users and Administrator pptx
Data base Users and Administrator   pptxData base Users and Administrator   pptx
Data base Users and Administrator pptx
AshokRachapalli1
 
Database Languages power point presentation
Database Languages power point presentationDatabase Languages power point presentation
Database Languages power point presentation
AshokRachapalli1
 
Relational Algebra in DBMS power ppoint pesenetation
Relational Algebra in DBMS power ppoint pesenetationRelational Algebra in DBMS power ppoint pesenetation
Relational Algebra in DBMS power ppoint pesenetation
AshokRachapalli1
 
Multi-Threading in Java power point presenetation
Multi-Threading in Java power point presenetationMulti-Threading in Java power point presenetation
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
ARRAYS in java with in details presentation.ppt
ARRAYS in java with in details presentation.pptARRAYS in java with in details presentation.ppt
ARRAYS in java with in details presentation.ppt
AshokRachapalli1
 
lecture-a-java-review .. this review ppt will help to the lectureres
lecture-a-java-review .. this review ppt will help to the lecturereslecture-a-java-review .. this review ppt will help to the lectureres
lecture-a-java-review .. this review ppt will help to the lectureres
AshokRachapalli1
 
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
AshokRachapalli1
 
joins in dbms its describes about how joins are important and necessity in d...
joins in dbms  its describes about how joins are important and necessity in d...joins in dbms  its describes about how joins are important and necessity in d...
joins in dbms its describes about how joins are important and necessity in d...
AshokRachapalli1
 
6.Database Languages lab-1.pptx
6.Database Languages lab-1.pptx6.Database Languages lab-1.pptx
6.Database Languages lab-1.pptx
AshokRachapalli1
 
Chapter5 (1).ppt
Chapter5 (1).pptChapter5 (1).ppt
Chapter5 (1).ppt
AshokRachapalli1
 
Cache Memory.pptx
Cache Memory.pptxCache Memory.pptx
Cache Memory.pptx
AshokRachapalli1
 
Addressing Modes.pptx
Addressing Modes.pptxAddressing Modes.pptx
Addressing Modes.pptx
AshokRachapalli1
 
inputoutputorganization-140722085906-phpapp01.pptx
inputoutputorganization-140722085906-phpapp01.pptxinputoutputorganization-140722085906-phpapp01.pptx
inputoutputorganization-140722085906-phpapp01.pptx
AshokRachapalli1
 
NOV11 virtual memory.ppt
NOV11 virtual memory.pptNOV11 virtual memory.ppt
NOV11 virtual memory.ppt
AshokRachapalli1
 
DATA MODEL Power point presentation for dbms
DATA MODEL Power point presentation for dbmsDATA MODEL Power point presentation for dbms
DATA MODEL Power point presentation for dbms
AshokRachapalli1
 
WEEK-2 DML and operators power point presentation
WEEK-2 DML and operators power point presentationWEEK-2 DML and operators power point presentation
WEEK-2 DML and operators power point presentation
AshokRachapalli1
 
Relational Algebra in DBMS 2025 power point
Relational Algebra in DBMS 2025 power pointRelational Algebra in DBMS 2025 power point
Relational Algebra in DBMS 2025 power point
AshokRachapalli1
 
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
CLOSURE OF AN ATTRIBUTE powerpontpresentatioCLOSURE OF AN ATTRIBUTE powerpontpresentatio
CLOSURE OF AN ATTRIBUTE powerpontpresentatio
AshokRachapalli1
 
Relational algebra in database management system
Relational algebra in database management systemRelational algebra in database management system
Relational algebra in database management system
AshokRachapalli1
 
DBMS-3.1 Normalization upto boyscodd normal form
DBMS-3.1 Normalization upto boyscodd normal formDBMS-3.1 Normalization upto boyscodd normal form
DBMS-3.1 Normalization upto boyscodd normal form
AshokRachapalli1
 
Data base Users and Administrator pptx
Data base Users and Administrator   pptxData base Users and Administrator   pptx
Data base Users and Administrator pptx
AshokRachapalli1
 
Database Languages power point presentation
Database Languages power point presentationDatabase Languages power point presentation
Database Languages power point presentation
AshokRachapalli1
 
Relational Algebra in DBMS power ppoint pesenetation
Relational Algebra in DBMS power ppoint pesenetationRelational Algebra in DBMS power ppoint pesenetation
Relational Algebra in DBMS power ppoint pesenetation
AshokRachapalli1
 
Multi-Threading in Java power point presenetation
Multi-Threading in Java power point presenetationMulti-Threading in Java power point presenetation
Multi-Threading in Java power point presenetation
AshokRachapalli1
 
ARRAYS in java with in details presentation.ppt
ARRAYS in java with in details presentation.pptARRAYS in java with in details presentation.ppt
ARRAYS in java with in details presentation.ppt
AshokRachapalli1
 
lecture-a-java-review .. this review ppt will help to the lectureres
lecture-a-java-review .. this review ppt will help to the lecturereslecture-a-java-review .. this review ppt will help to the lectureres
lecture-a-java-review .. this review ppt will help to the lectureres
AshokRachapalli1
 
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
17.INTRODUCTION TO SCHEMA REFINEMENT.pptx
AshokRachapalli1
 
joins in dbms its describes about how joins are important and necessity in d...
joins in dbms  its describes about how joins are important and necessity in d...joins in dbms  its describes about how joins are important and necessity in d...
joins in dbms its describes about how joins are important and necessity in d...
AshokRachapalli1
 
6.Database Languages lab-1.pptx
6.Database Languages lab-1.pptx6.Database Languages lab-1.pptx
6.Database Languages lab-1.pptx
AshokRachapalli1
 
inputoutputorganization-140722085906-phpapp01.pptx
inputoutputorganization-140722085906-phpapp01.pptxinputoutputorganization-140722085906-phpapp01.pptx
inputoutputorganization-140722085906-phpapp01.pptx
AshokRachapalli1
 
Ad

Recently uploaded (20)

How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdfBiophysics Chapter 3 Methods of Studying Macromolecules.pdf
Biophysics Chapter 3 Methods of Studying Macromolecules.pdf
PKLI-Institute of Nursing and Allied Health Sciences Lahore , Pakistan.
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Ad

using Java Exception Handling in Java.pptx

  • 2. What is an Exception in Java? • An exception is an unwanted or unexpected event that occurs during the execution of the program, that disrupts the flow of the program. • For example, if a user is trying to divide an integer by 0 then it is an exception, as it is not possible mathematically. • There are various types of interruptions while executing any program like errors, exceptions, and bugs. These interruptions can be due to programming mistakes or due to system issues. Depending on the conditions they can be classified as errors and exceptions. • Java has classes that are used to handle built-in exceptions and provision to create user-defined exceptions.
  • 3. 1. Exception • Exceptions are unwanted conditions that disrupt the flow of the program. • Exceptions usually occur due to the code and can be recovered. • Exceptions can be of both checked(exceptions that are checked by the compiler) and unchecked(exceptions that cannot be checked by the compiler) type. • They can occur at both run time and compile time. • In Java, exceptions belong to java.lang.Exception class.
  • 4. 2. Error • An error is also an unwanted condition but it is caused due to lack of resources and indicates a serious problem. • Errors are irrecoverable, they cannot be handled by the programmers. • Errors are of unchecked type only. • They can occur only at run time. • In java, errors belong to java.lang.error class. • Eg: OutOfMemmoryError.
  • 5. What is Exception Handling in java? • Exception handling in java is a mechanism to handle unwanted interruptions like exceptions and continue with the normal flow of the program. • Java uses try-catch blocks and other keywords like finally, throw, and throws to handle exceptions. • JVM(Java Virtual Machine) by default handles exceptions, when an exception is raised it will halt the execution of the program and throw the occurred exception.
  • 6. Why Handle Java Exception? • We handle exceptions in java to make sure the program executes properly without any halt, which occurs when an exception is raised. • These exceptions are runtime as well as compile-time. • They may be minor exceptions but can cause a problem in executions of the program, hence it becomes necessary to handle java exceptions. If java exceptions are not handled, programs may crash and execution is halted in between. • For example, if there is a program with some lines of code and an exception occurs a mid-way after executing certain lines of code, in this case, the execution terminates abruptly. • But if the programmer handles the exceptions explicitly, all the statements of code are executed properly and the flow of the program is maintained.
  • 7. Example program • class SampleCode • { • public static void main(String args[]) • { • Sysytem.out.println("Hello World!"); • int a = 10; • int b = 0; • System.out.println(a / b); • System.out.println("Welcome to java programming."); • System.out.println("Bye.") • } • }
  • 8. Output • Hello World! • Exception in thread "main" java.lang.ArithmeticException: / by zero • at SampleException.main(SampleException.java:8) • In the above code, the first three lines in the main method are executed properly. • At the 4th line, an integer is divided by 0, which is not possible and an exception is raised by JVM(Java Virtual Machine). • In this case, the exception is not handled by the programmer which will halt the program in between by throwing the exception, and the rest of the lines of code won't be executed.
  • 9. How does JVM handles an Exception? • Java exceptions raised during the program execution are nothing but objects of the respective exception class in the hierarchy shown above. • The exceptions have a naming and inheritance hierarchy to the main exception class in java i.e. Throwable class. • All java exception objects support the toString() method, which returns the full name of the exception class as an output to the command prompt, which helps to understand the exceptional condition. • Whenever an exception has occurred inside a method, the method creates an exception object and hands it over to JVM. • This object contains the name and description of the exception and the current state of the program where the exception has occurred. • This is called the process of object creation and handing it over to JVM is known as throwing an Exception. • This object is an exception that is further handled by JVM.
  • 10. How does JVM handles an Exception? • When an exception is raised there is an ordered list of the methods that had been called by JVM to get the method where the exception has occurred this list is called Call Stack. • JVM searches through this call stack to get the proper code to handle the occurred exception, this code block is known as an Exception handler. • When an appropriate handler is found JVM handles the exception according to the code in the handler and shows the state of the program.
  • 11. Major reasons why an exception Occurs • Invalid user input • Device failure • Loss of network connection • Physical limitations (out-of-disk memory) • Code errors • Out of bound • Null reference • Type mismatch • Opening an unavailable file • Database errors • Arithmetic errors
  • 12. Hierarchy of Java Exception Classes • As java is an object-oriented language every class extends the Object class. All exceptions and errors are subclasses of class Throwable. • Throwable is the base/superclass of exception handling hierarchy in java. This class is further extended in different classes like exception, error, and so on.
  • 13. Exception Hierarchy • All exception and error types are subclasses of the class Throwable, which is the base class of the hierarchy. • One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. • Another branch, Error is used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error.
  • 14. Hierarchy of Java Exception Classes
  • 16. Types of Exceptions • Java defines several types of exceptions that relate to its various class libraries. Java also allows users to define their own exceptions.
  • 17. Types of Exceptions Handling in Java • 1. Checked Exceptions • Checked exceptions are those exceptions that are checked at compile time by the compiler. • The program will not compile if they are not handled. • These exceptions are child classes of the Exception class. • IOException, ClassNotFoundException, InvocationTargetException, and SQL Exception are a few of the checked exceptions in Java.
  • 18. Types of Exceptions Handling in Java • 2. Unchecked Exceptions • Unchecked exceptions are those exceptions that are checked at run time by JVM, as the compiler cannot check unchecked exceptions, • The programs with unchecked exceptions get compiled successfully but they give runtime errors if not handled. • These are child classes of Runtime Exception Class. • ArithmeticException, NullPointerException, NumberFormatException, IndexOutOfBoundException are a few of the unchecked exceptions in Java.
  • 19. How does a Programmer Handles an Exception? • Customized exception handling in java is achieved using five keywords: try, catch, throw, throws, and finally. Here is how these keywords work in short. • Try block contains the program statements that may raise an exception. • Catch block catches the raised exception and handles it. • Throw keyword is used to explicitly throw an exception. • Throws keyword is used to declare an exception. • Finally block contains statements that must be executed after the try block.
  • 20. Example of Exception Handling in Java • class ExceptionExample { • public static void main(String args[]) { • try { • // Code that can raise exception • int div = 509 / 0; • } catch (ArithmeticException e) { • System.out.println(e); • } • System.out.println("End of code"); • } • } • Output: • java.lang.ArithmeticException: / by zero • End of code
  • 21. 1. try block • try block is used to execute doubtful statements which can throw exceptions. • try block can have multiple statements. • Try block cannot be executed on itself, there has to be at least one catch block or finally block with a try block. • When any exception occurs in a try block, the appropriate exception object will be redirected to the catch block, this catch block will handle the exception according to statements in it and continue the further execution. • The control of execution goes from the try block to the catch block once an exception occurs. • Syntax • try { • //Doubtfull Statements. • }
  • 22. 2. catch block • catch block is used to give a solution or alternative for an exception. • catch block is used to handle the exception by declaring the type of exception within the parameter. • The declared exception must be the parent class exception or the generated exception type in the exception class hierarchy or a user-defined exception. • You can use multiple catch blocks with a single try block. • Syntax • try { • //Doubtful Statements • } • catch(Exception e) • { • }
  • 23. 1. try-catch block • public class Main { • public static void main(String[ ] args) { • try { • int[] myNumbers = {10, 1, 2, 3, 5, 11}; • System.out.println(myNumbers[10]); • } catch (Exception e) { • System.out.println("Something went wrong."); • } • } • } • Output: • Something went wrong.
  • 24. • In this program, the user has declared an array myNumbers in the try block, which has some numbers stored in it. And the user is trying to access an element of the array that is stored at the 10th position. • But array has only 6 elements and the highest address position is 5. By doing this user is trying to access an element that is not present in the array, this will raise an exception, and the catch block will get executed.
  • 25. 2. Multiple Catch Blocks • Java can have a single try block and multiple catch blocks and a relevant catch block gets executed. • Example 1: • Here we are giving doubtful statements in a try block and using multiple catch blocks to handle the exception that will occur according to the statement.
  • 26. • public class MultipleCatchBlock1 { • public static void main(String[] args) { • try { • int a[] = new int[5]; • a[5] = 30 / 0; • } catch (ArithmeticException e) { • System.out.println("Arithmetic Exception occurs"); • } catch (ArrayIndexOutOfBoundsException e) { • System.out.println("ArrayIndexOutOfBounds Exception occurs"); • } catch (Exception e) { • System.out.println("Parent Exception occurs"); • } • System.out.println("End of the code"); • } • } • Output: • Arithmetic Exception occurs • End of the code
  • 27. • In this example, the try block has doubtful statements that are trying to divide an integer by 0 and 3 catch blocks which have mentioned the exceptions that can handle. • After execution of the try block, the Arithmetic Exception is raised and JVM starts to search for the catch block to handle the same. • JVM will find the first catch block that can handle the raised exception, and control will be passed to that catch block. • After the exception is handled the flow of the program comes out from try-catch block and it will execute the rest of the code.
  • 28. • public class MultipleCatchBlock2 { • public static void main(String[] args) { • try { • int a[] = new int[5]; • System.out.println(a[10]); • } catch (ArithmeticException e) { • System.out.println("Arithmetic Exception occurs"); • } catch (ArrayIndexOutOfBoundsException e) { • System.out.println("ArrayIndexOutOfBounds Exception occurs"); • } catch (Exception e) { • System.out.println("Parent Exception occurs"); • } • System.out.println("rest of the code"); • } • } • Output: • ArrayIndexOutOfBounds Exception occurs • rest of the code
  • 29. • In this example, try block has doubtful statements that are trying to access elements that are not present in an array and 3 catch blocks that have mentioned the exceptions that can handle. • After execution of try block, ArrayIndexOutOfBounds Exception is raised and JVM starts to search for the catch block to handle the same. • JVM will find the second catch block that can handle the raised exception, and control will be passed to that catch block. • After the exception is handled the flow of the program comes out from try-catch block and it will execute rest of the code.
  • 30. 3. Nested Try Catch • class NestingDemo { • public static void main(String args[]) { • //main try-block • try { • //try-block2 • try { • //try-block3 • try { • int arr[] = { • 1, • 2, • 3, • 4 • }; • /* I'm trying to display the value of • * an element which doesn't exist. The • * code should throw an exception • */ • System.out.println(arr[10]); • } catch (ArithmeticException e) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in try-block3"); • } • } catch (ArithmeticException e) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in try-block2"); • } • } catch (ArithmeticException e3) { • System.out.print("Arithmetic Exception"); • System.out.println(" handled in main try-block"); • } catch (ArrayIndexOutOfBoundsException e4) { • System.out.print("ArrayIndexOutOfBoundsException"); • System.out.println(" handled in main try-block"); • } catch (Exception e5) { • System.out.print("Exception"); • System.out.println(" handled in main try-block"); • } • } • } • Output: • ArrayIndexOutOfBoundsException handled in main try-block
  • 31. 3. Nested Try Catch • As you can see that the ArrayIndexOutOfBoundsException occurred in the grandchild try-block3. • Since try-block3 is not handling this exception, the control then gets transferred to the parent try-block2 and looked for the catch handlers in try-block2. • Since the try-block2 is also not handling that exception, the control gets transferred to the main (grandparent) try-block where it found the appropriate catch block for an exception. • We can use the finally block after the main try-catch block if required.
  • 32. 4. finally block • finally block is associated with a try, catch block. • It is executed every time irrespective of exception is thrown or not. • finally block is used to execute important statements such as closing statement, release the resources, and release memory also. • finally block can be used with try block with or without catch block.
  • 33. Syntax • try • { • //Doubtful Statements • } • catch(Exception e) • { • • } • finally • { • //Close resources • }
  • 34. Example: • public class Main { • public static void main(String[] args) { • try { • int data = 100/0; • System.out.println(data); • } catch (Exception e) { • System.out.println("Can't divide integer by 0!"); • } finally { • System.out.println("The 'try catch' is finished."); • } • } • } • Output: • Can't divide integer by 0! • The 'try catch' is finished. • Here, after the execution of try and catch blocks, finally block gets executed. finally block gets executed even if the catch block is not executed.
  • 35. throw • 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. • Syntax in Java throw • throw Instance • Example: • throw new ArithmeticException("/ by zero"); • But this exception i.e., Instance must be of type Throwable or a subclass of Throwable.
  • 36. 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, controlled 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.
  • 37. Throw Keyword • // Java program that demonstrates the use of throw • class ThrowExcep { • static void fun() • { • try { • throw new NullPointerException("demo"); • } • catch (NullPointerException e) { • System.out.println("Caught inside fun()."); • throw e; // rethrowing the exception • } • } • public static void main(String args[]) • { • try { • fun(); • } • catch (NullPointerException e) { • System.out.println("Caught in main."); • } • } • } • Output • Caught inside fun(). • Caught in main.
  • 38. Throw Keyword • // Java program that demonstrates • // the use of throw • class Test { • public static void main(String[] args) • { • System.out.println(1 / 0); • } • } • Output • Exception in thread "main" java.lang.ArithmeticException: / by zero
  • 39. Java throws • throws is a keyword in Java that is used in the signature of a 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. • Syntax of Java throws • type method_name(parameters) throws exception_list exception_list is a comma separated list of all the exceptions which a method might throw.
  • 40. Java throws • In a program, if there is a chance of raising an exception then the compiler always warns us about it and compulsorily we should handle that checked exception, Otherwise, we will get compile time error saying unreported exception XXX must be caught or declared to be thrown. To prevent this compile time error we can handle the exception in two ways: • By using try catch • By using the throws keyword • We can use the throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then the caller method is responsible to handle that exception.
  • 41. Java throws Examples • // Java program to illustrate error in case • // of unhandled exception • class tst { • public static void main(String[] args) • { • Thread.sleep(10000); • System.out.println("Hello Students"); • } • } • Output • error: unreported exception InterruptedException; must be caught or declared to be thrown • Explanation • In the above program, we are getting compile time error because there is a chance of exception if the main thread is going to sleep, other threads get the chance to execute the main() method which will cause InterruptedException.
  • 42. Java throws Examples • // Java program to illustrate throws • class tst { • public static void main(String[] args) • throws InterruptedException • { • Thread.sleep(10000); • System.out.println("Hello Students"); • } • } • Output • Hello Students • Explanation • In the above program, by using the throws keyword we handled the InterruptedException and we will get the output as Hello Geeks
  • 43. Java throws Examples • // Java program to demonstrate working of throws • class ThrowsExecp { • static void fun() throws IllegalAccessException • { • System.out.println("Inside fun(). "); • throw new IllegalAccessException("demo"); • } • public static void main(String args[]) • { • try { • fun(); • } • catch (IllegalAccessException e) { • System.out.println("caught in main."); • } • } • } • Output • Inside fun(). caught in main.
  • 44. Java throws Keyword • throws keyword is required only for checked exceptions and usage of the throws keyword for unchecked exceptions is meaningless. • throws keyword is required only to convince the compiler and usage of the throws keyword does not prevent abnormal termination of the program. • With the help of the throws keyword, we can provide information to the caller of the method about the exception.
  • 45. Java Custom Exception • In Java, we can create our own exceptions that are derived classes of the Exception class. Creating our own Exception is known as custom exception or user-defined exception. • Basically, Java custom exceptions are used to customize the exception according to user need.
  • 46. Java Custom Exception • Consider the example 1 in which InvalidAgeException class extends the Exception class. • Using the custom exception, we can have your own exception and message. Here, we have passed a string to the constructor of superclass i.e. Exception class that can be obtained using getMessage() method on the object we have created.
  • 47. Java Custom Exception • Following are few of the reasons to use custom exceptions: • To catch and provide specific treatment to a subset of existing Java exceptions. • Business logic exceptions: These are the exceptions related to business logic and workflow. It is useful for the application users or the developers to understand the exact problem. • In order to create custom exception, we need to extend Exception class that belongs to java.lang package.
  • 48. Example • Consider the following example, where we create a custom exception named WrongFileNameException: • public class WrongFileNameException extends Exception • { • public WrongFileNameException(String errorMessage) • { • super(errorMessage); • } • }