User-defined Custom Exception in Java

An exception is an issue (run time error) that occurred during the execution of a program. When an exception occurred the program gets terminated abruptly and, the code past the line that generated the exception never gets executed.

Java provides us the facility to create our own exceptions which are basically derived classes of Exception. Creating our own Exception is known as a custom exception or user-defined exception. Basically, Java custom exceptions are used to customize the exception according to user needs. In simple words, we can say that a User-Defined Exception or custom exception is creating your own exception class and throwing that exception using the ‘throw’ keyword.


Following are a 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 a custom exception, we need to extend the Exception class that belongs to java.lang package.

Example: We pass the string to the constructor of the superclass- Exception which is obtained using the “getMessage()” function on the object created.


File Handling in Java

In Java, with the help of File Class, we can work with files. This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.


what is file handling in java

This File Class is inside the java.io package. The File class can be used by creating an object of the class and then specifying the name of the file.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Exception and file handling in java example

1.Define a method that would sort an array of integers. Incorporate Exception handling mechanism for ArrayIndexOutOfBoundsException situation.

code in java:

import java.util.Arrays;

public class main{
   
    public static void main(String[] args)
    {
        int ar[] = { 10, 25, 3, 45, 15 };
        Arrays.sort(ar);
        for (int i = 0; i <= ar.length; i++)
            System.out.println(ar[i]);
    }
}

output:

3
10
Exception in thread "main" 15
25
45
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5


2.Write a program to read a name from user & display it on screen. The program shall throw an exception when the length of name is more than 15 characters. Design your own exception handling mechanism.

code in java:

import java.util.Scanner;

// A Class that represents use-defined exception
class MyException extends Exception {
    public MyException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}

// A Class that uses above MyException
public class main {
    // Driver Program
    public static void main(String args[])
    {      
        Scanner scan=new Scanner(System.in);
        System.out.print("Enter String :");
        String s = scan.nextLine();
        try {
            if(s.length()>15)
            // Throw an object of user defined exception
               throw new MyException(s);
        }
        catch (MyException ex) {
            System.out.println("Exception Caught");        
        }
    }
}


3.Write a program to sort the file contents i.e. List of Names in alphabetical order. Display file contents after sorting.

java code:

import java.io.File;
// Import this class for handling errors
import java.io.FileNotFoundException;
// Import the Scanner class to read content from text files
import java.util.Scanner;

public class A6Q4 {
    public static void main(String[] args)
    {
        try {
            File Obj = new File("myfile.txt");
            Scanner Reader = new Scanner(Obj);
            while (Reader.hasNextLine()) {
                String data = Reader.nextLine();
                System.out.println(data);
            }
            Reader.close();
        }
        catch (FileNotFoundException e) {
            System.out.println("An error has occurred.");
            e.printStackTrace();
        }
    }
}


output:

4.Read a file, convert lower case characters to upper case, remove special characters, write the output to another file and display the contents of a new file.

java code:
import java.util.*;
import java.io.*;
public class main {
    public static void main(String[] args) throws IOException     {

        File in = new File("text1.txt");  
        FileWriter writer=null;      
        try
        {
            FileReader fr = new FileReader(in);
            ArrayList<Integer> chr = new ArrayList<Integer>();    
            int c;            
            while ((c = fr.read()) != -1) {    
                chr.add(c);
            }
                System.out.print((char)c + "");
         

            writer = new FileWriter("text2.txt");
            System.out.printf("\nNew File Contents are...\n");
            for(int s: chr)
            {                
                if((s>=65 && s<=90) || s==32)
               
                {
                    writer.write((char)s);
                    System.out.print((char)s);
                }
                else if(s<=122 && s>=97 )
                {
                    s=s-32;
                    System.out.print((char)s);
                    writer.write((char)s);
                }      
                else if(s<65)
                {          
                    continue;
                }
            }
             }        
        catch(IOException e)
        {
            e.printStackTrace();
            System.out.println("Exception Handled!");
        }      
        finally
        {
            System.out.printf("\nFinished...");
            if (writer != null) {            
                writer.close();
                }
        }
       
    }
}
 







Any Queries feel free to contact