Returning a localized Exception

Throwable has a method called getLocalizedMessage, designed so that you can return a message in a language different than the standard getMessage language. By default, getLocalizedMessage returns the same as getMessage, but when you subclass Exception, you can provide your own implementation and preferably look up the localized message using a ResourceBundle.

This example introduces a Download class designed such that it can only handle the HTTP protocol. If it’s not, it will throw our exception DownloadProtocolException. The exception is caught and the message is printed both in the default locale language and a dutch one.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      try {
         Download d = new Download("ftp://microsoft.com/download/ie5.exe");
         d.start();
      }
      catch(DownloadProtocolException e) {
         System.out.println(e.getMessage());
         System.out.println(e.getLocalizedMessage(new Locale("nl", "BE")));
      }    
   }
}
 
class Download
{
   String url;
 
   public Download(String url) throws DownloadProtocolException {
      if (!url.startsWith("http://")) {
         throw new DownloadProtocolException(url);
      }
   }
 
   public void start() {
      // . . .
   }
}
 
class DownloadProtocolException extends Exception {
   private String url;
 
   public DownloadProtocolException(String url) {
      this.url = url;
   }
 
   public String getMessage() {
      return getLocalizedMessage(Locale.getDefault());
   }
   
   public String getLocalizedMessage(Locale locale) {
      ResourceBundle rb = ResourceBundle.getBundle("ErrorMessages", locale);
      return rb.getString("DownloadProtocolException") + ": " + url;
   }
}

ErrorMessages.properties:

DownloadProtocolException=Wrong protocol (only supports HTTP protocol)

ErrorMessages_nl_BE.properties:

DownloadProtocolException=Fout protocol (ondersteund slechts HTTP protocol)

Make sure these .properties can be found through a path in the classpath.

Running the app outputs:

Wrong protocol (only supports HTTP protocol): ftp://microsoft.com/download/ie5.exe
Fout protocol (ondersteund slechts HTTP protocol): ftp://microsoft.com/download/ie5.exe