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:
output:
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: