0% found this document useful (0 votes)
25 views37 pages

14.exception Handling - Try Catch

The document discusses exception handling in Java. It defines what exceptions are, different types of exceptions like checked exceptions and unchecked exceptions, and how to handle exceptions using try, catch, throw and throws keywords.

Uploaded by

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

14.exception Handling - Try Catch

The document discusses exception handling in Java. It defines what exceptions are, different types of exceptions like checked exceptions and unchecked exceptions, and how to handle exceptions using try, catch, throw and throws keywords.

Uploaded by

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

EXCEPTION HANDLING

EXCEPTION
HANDLING
Exception is anything that does not follow the rule
Thrower

Mob
Pho
Catc
Mobile
Phone Thrower
Catcher
Mobile
Phone Thrower
Catcher
Mobile
Phone Thrower
Catcher
Mobile
Phone Thrower
Catcher

Late
Comer
Catcher
ADVANTAGES OF THE APPROACH

• Preventing issues from overruling

your main stream activities

• Separating the main stream activities

from issue handling process

• Reusing the same exception handlers


EXCEPTION IN PROGRAMS??

• Any problem that may occur during


the execution of a program.
• Your program can encounter abnormal
situations during run time
The Exception Handling in Java is one of the powerful mechanism to handle the
runtime errors so that the normal flow of the application can be maintained.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Dictionary Meaning: Exception is an abnormal condition.

To avoid abnormal termination of a program.


Java Exception
hierarchy

Here is a simplified
diagram of the
exception hierarchy
in Java.
• Errors
• Errors represent irrecoverable
conditions such as Java virtual
machine (JVM) running out of
memory, memory leaks, stack
overflow errors, library
incompatibility, infinite recursion,
etc.

• Errors are usually beyond the


control of the programmer and we
should not try to handle errors.
Exceptions

• Exceptions can be caught and handled by the program.

• When an exception occurs within a method, it creates an object. This


object is called the exception object.

• It contains information about the exception such as the name and


description of the exception and state of the program when the
exception occurred.
Java Exception Types

The exception hierarchy


also has two branches:
RuntimeException and
IOException.
We learned about Java exceptions. We know that exceptions
abnormally terminate the execution of a program.

This is why it is important to handle exceptions.


• List of different approaches to
handle exceptions in Java.

• try...catch block
• finally block
• throw and throws keyword
Try

Throw

Catch

Throws

Finally
Keyword Description
try The "try" keyword is used to specify a block where we should
place an exception code. It means we can't use try block alone.
The try block must be followed by either catch or finally.
catch The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block
alone. It can be followed by finally block later.
finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It specifies
that there may occur an exception in the method. It doesn't throw
an exception. It is always used with method signature.
Try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Try
{
//code that may throw an exception
}
catch(Exception 1)
{
}
catch(Exception 2)
{
}
Syntax of try-finally block
1.try{
2.//code that may throw an exception
3.}finally
4.{
5.}
Types of Java Exceptions
There are mainly two types of exceptions: checked and
unchecked. An error is considered as the unchecked exception.
However, according to Oracle, there are three types of exceptions
namely:
1.Checked Exception
2.Unchecked Exception
3.Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions.
For example,
• IOException,
• SQLException,
• Class not found Exception
Checked exceptions are checked at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked
exceptions.
For example,
• ArithmeticException,
• NullPointerException,
• ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are
checked at runtime.
3) Error
Error is irrecoverable. Some example of errors are OutOfMemoryError,
VirtualMachineError, AssertionError etc.
ArithmeticException

1.int a=50/0; //ArithmeticException


public class ArithmeticExceptionExample
{
public static void main(String[] args) {
try
{
int result = 10 / 0;
System.out.println("Result is: " + result);
}
catch (ArithmeticException e)
{
System.out.println("Caught an arithmetic exception");
e.printStackTrace();
}
} }
NullPointerException
If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.

1.String s=null;
2.System.out.println(s.length());//NullPointerException
public class NullPointerExceptionExample {
public static void main(String[] args) {
// Declare a string variable and initialize it to null.
String text = null;

// Try to call the length() method on the string reference.


try {
int length = text.length();
System.out.println("Length of the string: " + length);
} catch (NullPointerException e) {
// Catch the NullPointerException and print a message.
System.out.println("Caught a NullPointerException.");
e.printStackTrace();
}
}
}
NumberFormatException
If the formatting of any variable or number is mismatched, it may result into
NumberFormatException. Suppose we have a string variable that has characters; converting this
variable into digit will cause NumberFormatException.

1.String str=“Java Programming";


2.int i=Integer.parseInt(str);//NumberFormatException
public class NumberFormatExceptionExample {
public static void main(String[] args) {
String number = "10a"; // This is not a purely numeric string.

try {
// This line will throw NumberFormatException because "10a" is
not a valid integer.
int result = Integer.parseInt(number);
System.out.println("The number is: " + result);
} catch (NumberFormatException e) {
// This block will catch the NumberFormatException.
System.out.println("NumberFormatException occurred: " +
e.getMessage());
}
}
}
ArrayIndexOutOfBounds Exception
When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
there may be other reasons to occur ArrayIndexOutOfBoundsException. Consider
the following statements.

1.int a[]=new int[5];


2.a[6]=50; //ArrayIndexOutOfBoundsException

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy