Skip to main content

Steps to create user define exception in java


How to create user define exception in java ?



Lets Create user defied exception in java . In this java tutorial i am using simple java code example where we accept number from user if number is one our program will throw user defied exception .

You will find video tutorial also for this assignment on you tube .




there are different types of exception in java mainly
1.User Defined   (user need to handle this exception)
2. System Defined ( it is defined by system itself/ Default  )


we are going to use following block in our program 
  
    try
        {   //Program logic goes here }
catch 
         {   }
finally 
         {    }



Steps to create user define exception in java 

  1. create user define exception class which extends Exception
  2. define constructor for user defined exception class put message into it
  3. define your actual class define exception condition and throw user defined exception using new keyword 
  4. catch using user defined exception  



Lets Create user define exception simple program in java

here is code sample 

_________________________
  
   class Positiv extends Exception
{
  Positiv()
  { 
      System.out.println("exception occur");
    }
}

class MyExcept
{
  public static void main(String s[])
  {  
   try{
        int a=1;
if(a==1)
throw new Positiv();
       }
catch(Exception Positiv){}
        }
}


______________________

Explanation:

lets we understand step by step user defined exception in java written above sample program

1.   Positiv is user defined class  extends Exception where we have written Positiv constructor where message is given "Exception Occur"

2. MyExcept is actul programming class where we implement try , catch block in try we write a logic that is if variable a is 1 then we have thrown our user defined exception using new keyword as 

if(a==1)
 throw new Positiv();
3.in catch block we catch our user define exception as 
catch(Exception Positiv){}


write a user defined exception using java . if user enter positive number throw positive exception if user enter negative number throw negative exception else throw zero exception .

solve java program.

DemoEx.java 



class Positive extends Exception
{ Positive () // constructor
{
System.out.println("positive excepion");
}
}

class Negative extends Exception
{ Negative () // constructor
{
System.out.println("Negative excepion");
}
}


class Zero extends Exception
{ Zero () // constructor
{
System.out.println("Zero excepion");
}
}




class DemoEx
{
public static void main(String s[])
{
try
{
int a=Integer.parseInt(s[0]);
if(a>0)
throw new Positive();
if(a==0)
throw new Zero();
if(a<0 font="">
 throw new Negative();
 
}  
 catch (Exception Positive){  }
   
}


}




What is an exception?
An Exception can be anything which interrupts the normal flow of the program. When an exception occurs program processing gets terminated and doesn’t continue further. In such cases we get a system generated error message.
 The good thing about exceptions is that they can be handled. We will cover the handling part later in this same tutorial.

When an exception can occur?
Exception can occur at runtime (known as runtime exceptions) as well as at compile-time (known Compile-time exceptions).
Reasons for Exceptions
There can be several reasons for an exception. For example, following situations can cause an exception –
 Opening a non-existing file, Network connection problem, Operands being manipulated are out of prescribed ranges, class file missing which was supposed to be loaded and so on.
Difference between error and exception
Errors indicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.

Exceptions are conditions within the code. A developer can handle such conditions and take necessary corrective actions. Few examples –
  • DivideByZero exception
  • NullPointerException
  • ArithmeticException
  • ArrayIndexOutOfBoundsException
Advantages of Exception Handling
  • Exception handling allows us to control the normal flow of the program by using exception handling in program.
  • It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.
  • It also gives us the scope of organizing and differentiating between different error types using a separate block of codes. This is done with the help of try-catch blocks.
Why to handle exception?
If an exception is raised, which has not been handled by programmer then program execution can get terminated and system prints a non user friendly error message.

Types of exceptions
There are two types of exceptions
Unchecked exceptions
  • NullPointerException
  • ArrayIndexOutOfBoundsException
  • ArithmeticException
  • IllegalArgumentException

Checked exceptions

Exception Handling Mechanism

In java, exception handling is done using five keywords,
  1. try
  2. catch
  3. throw
  4. throws
  5. finally






Comments

Labels

Show more

Popular posts from this blog

Calculator Program using jFrame

Calculator Program using jFrame java swing calculator example java jframe calculator source code java code for simple calculator using gui how to make a calculator in advance java using JFrame simple calculator program in java using frame simple calculator program in java source code write a code to create simple calculator using swing component import javax.swing.*; import java.awt.event.*; public class TextFieldExample extends JFrame implements ActionListener{     JTextField tf1,tf2,tf3;     JButton b1,b2; //declaration of control     TextFieldExample(){         JFrame f= new JFrame("Button click demo"); //         tf1=new JTextField();         tf1.setBounds(50,50,150,20);         tf2=new JTextField();         tf2.setBounds(50,100,150,20);         tf3=new JTextField();       ...

Java Program to delete record using JFrame and Prepaired Statement

Java Program to delete record using JFrame and Prepaired Statement Here is table Design  Create table demo using two column as id  and Dname , id is primary key  Program source code  +import javax.swing.*;   import java.awt.event.*;   import java.sql.*; public class FrameDelete extends JFrame implements ActionListener{       JTextField tf1,tf2,tf3;       JButton b1,b2;   JLabel l1,l2; Connection con;    PreparedStatement psmt;   int result; //declaration of control    FrameDelete(){           JFrame f= new JFrame("InsertDemo");   // l1=new JLabel("Enter RollNo"); l1.setBounds(150,10,150,50);         tf1=new JTextField();           tf1.setBounds(150,50,150,20);   tf3=new JTextField();           tf3.setBounds(1...

Basic java

java java java, learn java online free, classroom java tutorial, beginners java, java beginners, java programming,  basic java , basic java Tutorial,  basic java  Assignment           Hello friends ,       I am learning Basic java . my motive behind this blog is to help those want to learn Basic java online free of cost and grab each and every basic aspect of java programming .     you can find java tutorial from basic on this blog i will post each and every assignment of basic java with source code .          we will divide our course  in to Day work .          Let's start Day One  Basic Java Assignment for  Beginners      Basic Requirement to learn Java Programming Download following software             1. Text Editor (Notepad, Notepad++, Edit pad, Eclipse...