Custom Exception

You can write your own exception,those exceptions are called Custom Exception.
Custom Exception has to extends Exception class.
If you want to write RuntimeException then your Exception class should extend RuntimeException.

Example of Custom Exception:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class OverspeedingException extends Exception
    {
     
    }
public class CustomException
    {
        /**
        * @param args
        * @author BBS
        */
        static void checkSpeed(int speed) throws OverspeedingException
            {
                if (speed > 60)
                    {
                        throw new OverspeedingException();
                    }
                else
                    {
                        System.out.println("You are on safe speed");
                    }
            }
        public static void main(String[] args)
            {
                try
                    {
                        checkSpeed(80);
                    }
                catch (OverspeedingException e)
                    {
                        e.printStackTrace();
                    }
                System.out.println("Rest of the Programme....");
            }
    }

O/P:

java custom exception example