Let's learn java programming language with easy steps. This Java tutorial provides you complete knowledge about java technology.

Wednesday 28 June 2017

Custom Exception In Java


Java Custom Exception


Custom Exception In Java

Java custom exception means to create your own exception. You can create your own exception in java which is called custom exception or user-defined exception.

You can create your own exception and massages by the help of custom exception.

Let's create simple example of custom exception

Java Custom Exception Example

This is a simple custom example where we will throw own exception.

There we will create 2 files.

//File 1 : InvalidAgeException.java

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}

//File 2 : CustomExceptionExample.java

class CustomExceptionExample
{
static void validate(int age)throws InvalidAgeException
{
if(age < 18)
{
throw new InvalidAgeException("not valid age");
}
else
{
System.out.println("age is valid for vote");
}
}
public static void main(String args[])
{
try
{
validate(10);
}
catch(Exception e)
{
System.out.println("Exception is " +e);
}
}
}

save : InvalidAgeException.java, CustomExceptionExample.java
compile : CustomeExceptionExample.java
run : CustomeExceptionExample

output : Exception is InvalidAgeException : not valid age


In java Exception Handling, there are two types of exception :

  • checked exception : Checked exception are the exception which is checked at compile-time by the compiler is called checked exception e.g IOException, SQLException, FileNotFoundException .
  • unchecked exception : Unchecked exception are the exception which is not checked at compile-time , it is checked at run-time is called unchecked exception e.g ArithmeticException, NullPointerException, NumberFormatException, etc.

Custom Checked Exception

If the customer is able to recover from the exception, make it checked exception. When you create custom checked exception, extends java.lang.Exception.

//File 1 : NameNotFoundException.java

class NameNotFoundException extends Exception
{
NameNotFoundException(String s)
{
super(s);
}
}

//File 2 : CustomerService.java

class CustomerService
{
Customer findByName(String name)throws NameNotFoundException
{
if("".equals(name))
{
throw new NameNotFoundException("name is empty");
}
return new Customer(name);
}
public static void main(String args[])
{
CustomerService cs = new CustomerService();
{
try
{
Customer c = cs.findByName("");
}
catch(NameNotFoundException n)
{
e.printStackTrace();
}
}
}
}

Share:

2 comments:

Facebook Page Likes

Follow javatutorial95 on twitter

Popular Posts

Translate