Tutorials

Java Exception Handling


Custom Exception


We have learned so far there are several in-built features provided to handle various exceptions in java.

 

Inspite of the fact that java provides lots of in-built classes to handle exception in best possible ways but there are certain limitations with the in-built features. In practical world, we may want to throw our own customized exceptions.

Java creators understood this fact very well and provided the java programmars with the facility to create their own exception and use them as per their requirement. 

 

What is custom exception?

When a programmar wishes to create their own exception for their application instead of using the java provided ones, then those created exceptions are termed as custom exceptions

These are exception that are customized as per applications requirement.

 

Why custom exception is needed?

In practical world, we build various kind of applications. 

Its not compulsory that all of the code that is written will only throw ArithmeticException, ArrayIndexOutOfBoundException, FileNotFoundException, etc.

 

Suppose, you are writing code for creating an application for uploading file to your server. There is a restriction that file less than 10KB can only be uploaded at a time. 

Now you want to build a custom exception for this and provide a message to the user - "File more than 10KB not allowed".

 

How to create custom exception in java?

Your custom exception class needs to extend Exception class.

For example, You want to create InvalidFileSize class as the custom Exception class.


class InvalidFileSize extends Exception{

           InvalidFileSize(String str){

           super(str);

           }

}

 

 



Please Share this page
Views : 105
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!