3 different ways to print exception message in java

  • In Java there are three ways to find the details of the exception .
  • They are 
  1. Using an object of java.lang.Exception
  2. Using public void printStackTrace() method
  3. Using public String getMessage() method.

1.Using an object of java.lang.Exception

  •  An object of Exception class prints the name of the exception and nature of the exception.



Write a Java program get detailed message details using exception class object



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4. /**
  5.  * @www.instanceofjava.com
  6.  **/
  7.  public static void main(String[] args) {
  8.  
  9. try {
  10.  
  11. int x=1/0;
  12.             
  13. } catch (Exception e) {
  14.             System.out.println(e);
  15. }
  16.  
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArithmeticException: / by zero


 2.Using  public void printStackTrace() method


  • This is the method which is defined in java.lang.Throwable class and it is inherited into java.lang.Error class and java.lang.Exception class
  • This method will display the name of the exception and nature of the message and line number where exception has occurred.

Write a simple java example program to print exception message to console using printStacktrace() method



  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7. public static void main(String[] args) {

  8.  
  9.  try {
  10.           int a[]= new int[1];
  11.             a[1]=12
  12.             
  13. } catch (Exception e) {
  14.    e.printStackTrace();
  15.            
  16.  }
  17. }
  18.  
  19. }

 Output:


  1. java.lang.ArrayIndexOutOfBoundsException: 1
        at exceptions.ExceptionDetails.main(ExceptionDetails.java:13)

  3.Using public String getMessage() method

  •  This is also a method which is defined in java.lang.Throwable class and it is inherited in to both java.lanf.Error and java.lang.Exception classes.
  • This method will display the only exception message


Write a Java program print exception message using getMessage() method.


  1. package exceptions;
  2. public class ExceptionDetails {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.     public static void main(String[] args) {

  8.  
  9.         try {
  10.             int x=1/0;
  11.             
  12.         } catch (Exception e) {
  13.             System.out.println(e.getMessage());
  14.         }
  15.     }
  16.  
  17. }

 Output:


  1.  / by zero

print exception message

throw keyword in java with example

Throw keyword in java

  • Throw keyword is used to throw exception manually.
  • Whenever it is required to suspend the execution of the functionality based on the user defined logical error condition we will use this throw keyword to throw exception.
  • So we need to handle these exceptions also using try catch blocks.



 Java simple example Program to explain use of throw keyword in java


  1. package exceptions;
  2.  
  3. public class ThrowKeyword {
  4.  
  5.     
  6. public static void main(String[] args) {
  7.  
  8. try {
  9.             
  10.    throw new ArithmeticException();
  11.             
  12.             
  13. } catch (Exception e) {
  14.  
  15.    System.out.println(e);
  16.    e.printStackTrace();
  17. }
  18.  
  19. }
  20.  
  21. }

Output:



  1. java.lang.ArithmeticException
  2. java.lang.ArithmeticException
  3.     at exceptions.ThrowKeyword.main(ThrowKeyword.java:11)

Rules to use "throw" keyword in java
  • throw keyword must follow Throwable type of object.
  • It must be used only in method logic.
  • Since it is a transfer statement , we can not place statements after throw statement. It leads to compile time error Unreachable code



throw keyword in java


  •  We can throw user defined exception using throw keyword.

  1. //Custom exception
  2. package com.instanceofjavaforus;
  3. public class InvalidAgeException extends Exception {
  4.  InvaidAgeException(String msg){
  5.  super(msg);
  6.  }
  7. }
     

  1. package com.exceptions;
  2. public class ThrowDemo {

  3. public boolean isValidForVote(int age){
  4.  
  5.  try{
  6.    if(age<18){
  7.   throw new InvalidAgeException ("Invalid age for voting");
  8. }
  9.  }catch(Exception e){
  10.  System.out.println(e);
  11.  }
  12.   return false;
  13.  }
  14.  
  15. public static void main(String agrs[]){
  16.  
  17.  ThrowDemo obj= new ThrowDemo();
  18.    obj.isValidForVote(17);
  19.  
  20.   }
  21. }


 Output:


  1.  exceptions.InvalidAgeException: Invalid age for voting
  • We can throw predefined exceptions using throw keyword


  1. package com.instanceofjava;
  2.  
  3. public class ThrowKeyword{
  4. public void method(){
  5.  
  6.  try{
  7.   
  8.   throw new NullPointerException("Invalid age for voting");
  9. }
  10.  }catch(Exception e){
  11.  System.out.println(e);
  12.  }
  13.  }
  14.  
  15.   public static void main(String agrs[]){
  16.  
  17.  ThrowKeyword obj= new ThrowKeyword();
  18.  
  19.    obj.method();
  20.  
  21.   }
  22. }

 Output:


  1.  java.lang.NullPointerException: Invalid age for voting

Multiple catch blocks in java example

Is there any chance of getting multiple exception?

  • Lets see a java example programs which can raise multiple exceptions.


  1. package exceptions;
  2. public class MultipleCatchBlocks {
  3.  
  4.     /**
  5.      * @www.instanceofjava.com
  6.      */
  7.  
  8. public static void main(String[] args) {
  9.         
  10.         
  11.  int x=10;
  12.  int y=0;
  13.  
  14. try{
  15.             
  16.    int i=x/y;
  17.    int a[]=new int[2];
  18.    a[3]=12;
  19.             
  20. } catch(ArithmeticException e){
  21.             e.printStackTrace();
  22. }
  23.  
  24. }
  25.  
  26. }

Output:


  1. java.lang.ArithmeticException: / by zero
        at exceptions.MultipleCatchBlocks.main(MultipleCatchBlocks.java:15)

  •  Lets see second case:


multiple catch blocks in java




try with multiple catch blocks

  • In the 1st program there is a chance of getting two types of exceptions and we kept only one catch block with  ArithmeticException e . 
  • But there will be chance of getting ArrayIndexOutOfBoundsException too. 
  • So we need to keep multiple catch blocks in order to handle all those exceptions
  • Or else we can keep single catch block with super class Exception class object.

 




Multiple catch blocks for single try block:

 

  • One try can have multiple catch blocks 
  • Every try should and must be associated with at least one catch block.( try without catch)
  • Whenever an exception object is identified in try block and if there are multiple catch blocks then the priority for the catch block would be given based on order in which catch blocks are have been defined.
  • Highest priority would be always given to first catch block . If the first catch block can not handle the identified exception object then it considers the immediate next catch block.

Disadvantages of multiple catch blocks:
 
  •  We have to know the names of every corresponding exception class names.
  • We have to understand which statement is generating which exception class object.



Solution: 

  •  Define a single catch block so that it should be able to handle any kind of exceptions identified in the try block.
  • Exception class is the super class for all the exception classes.
  • To the reference of super class object we can assign any sub class object.

Can we have try without catch block in java

  • It is possible to have try block without catch block by using finally block
  • Java supports try with finally block
  • As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
  • We can place logic like connections closing or cleaning data  in finally.


Java Program to write try without catch block | try with finally block
  1. package exceptionsInterviewQuestions;
  2. public class TryWithoutCatch {
  3.  
  4.     
  5. public static void main(String[] args) {
  6.         
  7.         
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.             
  12. } finally{
  13.             
  14.             System.out.println("inside finally block");
  15. }
  16.  
  17. }
  18.  
  19. }



Output:


  1. inside try block
  2. inside finally block

  •  Finally block executes Even though the method have return type and try block returns something

Java Program to write try with finally block and try block returns some value

  1. package exceptionsInterviewQuestions;
  2.  
  3. public class TryWithFinally {
  4.  
  5. public static int method(){  
  6.   
  7.        
  8. try {
  9.             
  10.   System.out.println("inside try block");
  11.  
  12.  return 10;        
  13. } finally{
  14.             
  15.             System.out.println("inside finally block");
  16. }
  17.  
  18. }
  19.  
  20. public static void main(String[] args) {
  21.         
  22. System.out.println(method());
  23.  
  24. }
  25.  
  26. }

Output:


  1. inside try block
  2. inside finally block
  3. 10


What happens if exception raised in try block?

  • Even though exception raised in try block finally block executes.

try with finally block in java

Remove duplicates from arraylist without using collections

1.Write a Java program to remove duplicate elements from an arraylist without using collections (without using set)




  1. package arrayListRemoveduplicateElements;
  2. import java.util.ArrayList;
  3.  
  4. public class RemoveDuplicates {
  5. public static void main(String[] args){
  6.     
  7.     ArrayList<Object> al = new ArrayList<Object>();
  8.     
  9.     al.add("java");
  10.     al.add('a');
  11.     al.add('b');
  12.     al.add('a');
  13.     al.add("java");
  14.     al.add(10.3);
  15.     al.add('c');
  16.     al.add(14);
  17.     al.add("java");
  18.     al.add(12);
  19.     
  20. System.out.println("Before Remove Duplicate elements:"+al);
  21.  
  22. for(int i=0;i<al.size();i++){
  23.  
  24.  for(int j=i+1;j<al.size();j++){
  25.             if(al.get(i).equals(al.get(j))){
  26.                 al.remove(j);
  27.                 j--;
  28.             }
  29.     }
  30.  
  31.  }
  32.  
  33.     System.out.println("After Removing duplicate elements:"+al);
  34.  
  35. }
  36.  
  37. }



Output:

  1. Before Remove Duplicate elements:[java, a, b, a, java, 10.3, c, 14, java, 12]
  2. After Removing duplicate elements:[java, a, b, 10.3, c, 14, 12]

2. Write a Java program to remove duplicate elements from an array using Collections (Linkedhashset)

  1. package arrayListRemoveduplicateElements;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.HashSet;
  5. import java.util.List;
  6.  
  7. public class RemoveDuplicates {
  8.  
  9. public static void main(String[] args){
  10.     
  11.     List<String>  arraylist = new ArrayList<String>();
  12.     
  13.     arraylist.add("instanceofjava");
  14.     arraylist.add("Interview Questions");
  15.     arraylist.add("Interview Programs");
  16.     arraylist.add("java");
  17.     arraylist.add("Collections Interview Questions");
  18.     arraylist.add("instanceofjava");
  19.     arraylist.add("Java Experience Interview Questions");
  20.     
  21.     
  22.     System.out.println("Before Removing duplicate elements:"+arraylist);
  23.     
  24.     HashSet<String> hashset = new HashSet<String>();
  25.     
  26.     /* Adding ArrayList elements to the HashSet
  27.      * in order to remove the duplicate elements and 
  28.      * to preserve the insertion order.
  29.      */
  30.     hashset.addAll(arraylist);
  31.  
  32.     // Removing ArrayList elements
  33.     arraylist.clear();
  34.  
  35.     // Adding LinkedHashSet elements to the ArrayList
  36.     arraylist.addAll(hashset );
  37.  
  38.     System.out.println("After Removing duplicate elements:"+arraylist);
  39.  
  40. }
  41.  
  42. }



Output:
 


  1. Before Removing duplicate elements:[instanceofjava, Interview Questions, Interview
  2. Programs, java, Collections Interview Questions, instanceofjava, Java Experience Interview
  3. Questions]
  4. After Removing duplicate elements:[java, Collections Interview Questions, Java Experience
  5. Interview Questions, Interview Questions, instanceofjava, Interview Programs]


arraylist remove duplicates


Enum in java part 2

3. Enum Iteration in for-each loop:




  • You can obtain an array of all the possible values of a Java enum type by calling its static values() method. 
  • All enum types get a static values() method automatically by the Java compiler. Here is an example of iterating all values of an enum:
 
  1. for (Day day : Day.values()) {
  2.     System.out.println(day);
  3. }

  • If you run this code, then you will get the following output:


  1. SUNDAY
  2. MONDAY
  3. TUESDAY
  4. WEDNESDAY
  5. THURSDAY
  6. FRIDAY
  7. SATURDAY




4.    Enum fields:


  • It is possible to add fields to Java Enum. Each constant enum value gets these fields. The field values must be supplied to the constructor of the enum when defining the constants. 
  • Here is an example:

  1. public enum Day {
  2.     SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5),
  3. FRIDAY(6), SATURDAY(7); 
  4.  
  5.     private final int dayCode;
  6.     private Day(int dayCode) {
  7.         this.dayCode = dayCode;
  8.     }
  9.  
  10. }
  • The example above has a constructor which takes an int. The enum constructor sets the int field. When the constant enum values are defined, an int value is passed to the enum constructor.
  • The enum constructor must be either private or package scope (default). You cannot use public or protected constructors for a Java enum.

5. Enum Methods:

  • It is possible to add methods to Java Enum. Here I am showing an example that how to do it.

  1. public enum Day {
  2.  
  3.     SUNDAY(1), MONDAY(2), TUESDAY(3), WEDNESDAY(4), THURSDAY(5),
  4. FRIDAY(6), SATURDAY(7); 
  5.  
  6.     private final int dayCode;
  7.  
  8.     private Day(int dayCode) {
  9.         this.dayCode = dayCode;    
  10.      }
  11.     public int getDayCode() {
  12.         return this.dayCode;
  13.     }
  14.     
  15. }

  • It is possible to call an Enum method through a reference to one of the constant values. The following code will show you how to call Java Enum method.
  • Day day = Day.MONDAY;
  • System.out.println(day.getDayCode()); //which gives 2.Because the dayCode field for the Enum constant MONDAY is 2.
 Some details to know about enum:

  • Java enums extend the java.lang.Enum class implicitly, so your enum types cannot extend another class. Please refer the following code. This code is from Java API.
  1. public abstract class Enum<E extends Enum<E>> implements Comparable<E>,Serializable {
  2. // Enum class code in Java API
  3. }
  • If a Java enum contains fields and methods, the definition of fields and methods must always come after the list of constants in the enum. Additionally, the list of enum constants must be terminated by a semicolon;
  • Java does not support multiple inheritance, and enum also does not support for multiple inheritance.
  • Enums are type-safe. Enum has their own name-space. It means your enum will have a type for example “Day” in below example and you cannot assign any value other than specified in Enum Constants.
  • Enum constants are implicitly static and final and cannot be changed once created.
  • Enum can be safely compare using:
  • Switch-Case Statement
  • == Operator
  • .equals() method
  • You cannot create instance of enums by using new operator in Java because constructor of Enum in Java can only be private and Enums constants can only be created inside Enums itself.
  • Instance of Enum in Java is created when any Enum constants are first called or referenced in code
  •  An enum can be declared outside or inside a class, but NOT in a method.
  • An enum declared outside a class must NOT be marked static, final , abstract, protected , or private
  • Enums can contain constructors, methods, variables, and constant class bodies.
  • Enum constructors can have arguments, and can be overloaded.
  • Enum constructors can have arguments, and can be overloaded.
  • The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself

  1. package com.enum.exampleprogram;
  2.  
  3.  /**This is an Enum which indicates possible days in a week **/ 
  4.  
  5. public enum Day {
  6.     SUNDAY, MONDAY, TUESDAY, WEDNESDAY,THURSDAY, FRIDAY, SATURDAY;
  7. }


  1. package com.pamu.test;
  2. /** This class is an example of Enum  **/
  3. public class EnumTest {
  4.     Day day;
  5.     public EnumTest(Day day) {
  6.         this.day = day;
  7.     }
  8. //method to get descriptions of the respected days in a switch-statement.
  9.  
  10.  public void getDayDescription() {
  11.  
  12.  switch (day) {
  13.    case MONDAY:
  14.                System.out.println("Monday is First day in a week.");
  15.                 break;      
  16.   case FRIDAY:
  17.                 System.out.println("Friday is a partial working day.");
  18.                 break;        
  19.   case SATURDAY: 
  20.                 System.out.println("Saturday is a Weekend.");
  21.                 break;
  22.  case SUNDAY:
  23.                 System.out.println("Sunday is a Weekend.");
  24.                 break;               
  25.   default:
  26.                 System.out.println("Midweek days are working days.");
  27.                 break;
  28.         }
  29.     }
  30.     public static void main(String[] args) {
  31.  
  32.         EnumTest day1 = new EnumTest(Day.MONDAY);
  33.         day1.getDayDescription();
  34.  
  35.         EnumTest day2 = new EnumTest(Day.TUESDAY);
  36.         day2.getDayDescription();
  37.  
  38.         EnumTest day3 = new EnumTest(Day.WEDNESDAY);
  39.         day3.getDayDescription();
  40.  
  41.         EnumTest day5 = new EnumTest(Day.FRIDAY);
  42.         day5.getDayDescription();
  43.  
  44.         EnumTest day6 = new EnumTest(Day.SATURDAY);
  45.         day6.getDayDescription();
  46.  
  47.         EnumTest day7 = new EnumTest(Day.SUNDAY);
  48.         day7.getDayDescription();
  49.  
  50.     }
  51. }

Output:

  1. Monday is First day in a week.
  2. Midweek days are working days.
  3. Midweek days are working days.
  4. Friday is a partial working day.
  5. Saturday is a Weekend.
  6. Sunday is a Weekend.

Enum in java Example

Java Enum:
  • In this tutorial I will explain what is enum, how to use enum in different areas of a Java program and an example program on it.



  • An Enum type is a special data type which is added in Java 1.5 version. It is an abstract class in Java API which implements Cloneable and Serializable interfaces. It is used to define collection of constants. When you need a predefined list of values which do not represent some kind of numeric or textual data, at this moment, you have to use an enum.
  • Common examples include days of week (values of SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY), directions, and months in a year. Etc.
  • You can declare simple Java enum type with a syntax that is similar to the Java class declaration syntax. Let’s look at several short Java enum examples to get you started.

Enum declaration Example 1:

  1. public enum Day {
  2.  SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY 
  3. }


Enum declaration Example 2:

  1.  public enum Month{
  2. JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER,
  3. OCTOBER, NOVEMBER, DECEMBER
  4. }

  • Enums are constants; they are by default static and final. That’s why the names of an enum type's fields are in uppercase letters.
  • Make a note that the enum keyword which is used in place of class or interface. The Java enum keyword signals to the Java compiler that this type definition is an enum.
    You can refer to the constants in the enum above like this:
  •  
  1. Day day = Day.MONDAY;



  • Here the ‘day’ variable is of the type ‘Day’ which is the Java enum type defined in the example above. The ‘day’ variable can take one of the ‘Day’ enum constants as value (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY). In this case ‘day’ is set to MONDAY.
  • If you use enum instead of integers or String codes, you increase compile-time checking and avoid errors from passing in invalid constants, and you document which values are legal to use.
  • How to use a Java enum type in various areas in a Java Program:
  • We have seen how to declare simple Java enum types, let’s take a look at how to use them in various areas. We have to use a Java enum type in a variety of situations, including in a Java 5 for loop, in a switch statement, in an if/else statement, and more. For simple, Enum comparison, there are 3 ways to do it. They are, Switch-Case Statement, == Operator, .equals() method. Like that there are other places where you have to use Enum.
  • Let's take a look at how to use our simple enum types with each of these Java constructs.
  1. Enum in IF statement
  2. Enum in Switch statement
  3. Enum Iteration in for-each loop 
  4. Enum Fields 
  5. Enum Methods

1. Enum in IF statements:


  • We know Java Enums are constants. Sometimes, we have a requirement to compare a variable of Enum constant against the possible other constants in the Enum type. At this moment, we have to use IF statement as follows.
  • Day day = ----- //assign some Day constants to it.
     
  1. If(day ==Day.MONDAY){
  2. ….//your code
  3. } else if (day == Day.TUESDAY){
  4. ….//your code
  5. } else if (day == Day.WEDNESDAY){
  6. ….//your code
  7. } else if (day == Day. THURSDAY){
  8. ….//your code
  9. } else if (day == Day.FRIDAY){
  10. ….//your code
  11. } else if (day == Day.SATURDAY){
  12. ….//your code
  13. } else if (day == Day.SUNDAY){
  14. ….//your code
  15. }

  • Here, you can use “.equals()” instead of “==”. But, my preference is to use “==” because, it will never throws NullPointerException, safer at compile-time, runtime and faster.
  • The code snippet compares the ‘day’ variable against each of the possible other Enum constants in the ‘Day’ Enum.

2. Enums in Switch Statements:


  • Just assume that your Enum have lot of constants and you need to check a variable against the other values in Enum. For a small Enum IF Statement will be OK. If you use same IF statement for lot of Enum constants then our program will be increased and it is not a standard way to write a Java program. At this Situation, use Switch Statement instead of IF statement.
  • You can use enums in switch statements as follows:
  • Day day = ...  //assign some Day constant to it

  1. switch (day) { 
  2.     
  3. case SUNDAY   : //your code; break; 
  4. case MONDAY //your code; break;
  5. case TUESDAY    : //your code; break;     
  6. case WEDNESDAY    : //your code; break;
  7. case THURSDAY: //your code; break;
  8. case FRIDAY    : //your code; break;
  9. case SATURDAY    : //your code; break;
  10.  
  11. }

  • Here, give your code in the comments, “//your code”. The code should be a simple Java operation or a method call..etc 

Enum in java

3.Enum Iteration in for-each loop
4.Enum Fields
5.Enum Methods

Please click here  Enum in java part 2
Select Menu