Explain Throwable class in brief?


Throwable class is present in java.lang package.

Syntax:

public class Throwable

extends Object

implements Serializable

Throwable class is direct child class of Object class.

Throwable class extends Object class and implements Serializable interface.

Throwable class subclasses are Error class and Exception class.

Throwable class Constructors:

1.      public Throwable()

2.      public Throwable(String msg)

3.      public Throwable(String msg, Throwable cause)

4.      public Throwable(Throwable cause)

5.      protected Throwable(String message, Throwable cause,

                                                     boolean enableSuppression,

                                                     boolean writableStackTrace)

Throwable class Methods:

1.      public String getMessage()

2.      public String toString()

3.      public void printStackTrace()

4.      public String getLocalizedMessage()

Custom Exception Example in java


1: class TooYoungException extends RuntimeException {

2:

3: TooYoungException(String s) {

4: super(s);

5: }

6: }

7:

8: class TooOldException extends RuntimeException {

9:

10: TooOldException(String s) {

11: super(s);

12: }

13: }

14:

15: class CustomExceptionDemo {

16: public static void main(String[] args) {

17: int age = Integer.parseInt(args[0]);

18: if (age > 60) {

19: throw new TooYoungException(

20: “please wait some more time,we will contact you with mail”);

21:

22: } else if (age < 18) {

23: throw new TooOldException(“you crassed your age limit”);

24: } else {

25: System.out.println(“you will get best choice matches soon”);

26: }

27: }

28: }

OUTPUT :

image

Q) Difference Between final, finally, finalize?


final:

         It is the modifier applicable for classes methods and variables. For final classes we can’t create child classes i.e inheritance is not possible.

         final() methods can’t be override in child classes for final variables reassignments is not possible because they are constants.

finally:

          It is a block associated with try catch the main objective of finally block is to maintain cleanup code which should execute always.

 finalize:

       It is a method should be executed by the “Garbage Collector” just before destroying an object. The main objective of finalize method is to maintain cleanup code.

 Note:  

         when compared with finalize, finally is always recommended to maintain cleanup code because there is no guarantee for the exact behavior of “Garbage Collector” it is Virtual Machine Dependent.