0% found this document useful (0 votes)
31 views43 pages

Sessions 22, 23 Exception Handling

Uploaded by

snikith7
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)
31 views43 pages

Sessions 22, 23 Exception Handling

Uploaded by

snikith7
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/ 43

User-defined exceptions

• What are user-defined exceptions?:


• User-defined exceptions are exceptions that are created by the programmer.
• They are used to handle errors that are specific to the programmer's application.

• How to create a user-defined exception:


• To create a user-defined exception, you must create a new class that extends the
Exception class.
• The new class must have a constructor that takes a string as an argument.
• The string will be the error message that is displayed when the exception is thrown.
Example of a user-defined exception
Built-in exceptions
• What are built-in exceptions?:
• Built-in exceptions are exceptions that are provided by the Java language.
• They are used to handle common errors that can occur in any Java program.

• List of built-in exceptions:


• There are many built-in exceptions in Java. Some of the most common ones
include:
• ArithmeticException: Thrown when an arithmetic error occurs, such as division by zero.
• ArrayIndexOutOfBoundsException: Thrown when an attempt is made to access an element of an
array that is out of bounds.
• NullPointerException: Thrown when an attempt is made to use a null object.
Common Scenarios of Java
Exceptions
A scenario where NullPointerException
occurs
If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.
String s=null;
System.out.println(s.length()); //
NullPointerException
A scenario where NumberFormatException
occurs
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.
String s="abc";
int i=Integer.parseInt(s); //
NumberFormatException
A scenario where ArrayIndexOutOfBoundsException occurs

When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs. there may be
other reasons to occur ArrayIndexOutOfBoundsException. Consider the following statements.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Note:
 If an exception occurs at the particular statement in the try block, the rest of the block code
will not execute. So, it is recommended not to keep the code in try block that will not throw an
exception.
 Java try block must be followed by either catch or finally block.
Program for without
public class try and catch block.
TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output: Exception in thread "main" java.lang.ArithmeticException: / by zero

 As displayed in the above example, the rest of the code is not executed (in such case, the rest of the code statement
is not printed).

 There might be 100 lines of code after the exception. If the exception is not handled, all the code below the exception
won't be executed.
 Java 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 ( i.e.,
Exception) or the generated exception type. However, the good approach is to declare
the generated
 The catch blocktype
mustof be
exception.
used after the try block only. You can use multiple catch block
with a single try block.
Solution by exception handling
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}

Output: java.lang.ArithmeticException: / by zero


rest of the code
Examples:
public class TryCatchExample3
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will
not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}

}
Output: java.lang.ArithmeticException: / by zero
}
public class TryCatchExample4
{

public static void main(String[] args)


{
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exceptio
n class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}

}
Output: java.lang.ArithmeticException: / by zero
rest of the code
Let's see an example to print a custom message on exception.

public class TryCatchExample5


{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");

}
}

}
Output: Can't divided by zero
Let's see an example to resolve the exception in a catch block.

public class TryCatchExample6


{
public static void main(String[] args)
{
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
User Defined Exceptions

 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.
 In order to create custom exception, we need to extend Exception class that belongs to
java.lang package.
// class representing custom exception User Defined Exceptions
class InvalidAgeException extends Exception
{ // main method
public InvalidAgeException (String str) public static void main(String args[])
{ {
// calling the constructor of parent Exception try
super(str); {
} } // calling the method
// class that uses custom exception InvalidAgeException validate(13);
public class TestCustomException1 }
{ catch (InvalidAgeException ex)
// method to check the age {
static void validate (int age) throws System.out.println("Caught the exception");
InvalidAgeException{
if(age < 18){ // printing the message from InvalidAgeException
// throw an object of user defined exception object
throw new InvalidAgeException("age is not valid to System.out.println("Exception occured: " + ex);
vote"); }
}
else { System.out.println("rest of the code...");
System.out.println("welcome to vote"); } }
} }
// class representing custom exception
class MyCustomException extends Exception
{

// class that uses custom exception MyCustomException


public class TestCustomException2
{
// main method
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new MyCustomException();
}
catch (MyCustomException ex)
{
System.out.println("Caught the exception");
System.out.println(ex.getMessage());
}

System.out.println("rest of the code...");


}
}

You might also like