Site Search:

Use try-catch and throw statements

Back>

try-catch and throw
try-catch and throw


OCAJP have a chapter dedicated to Handling Exceptions.
OCPJP added more contents.

More checked exceptions:


  • java.text.ParseException
  • java.io.FileNotFoundException extends IOException

OCPJP Constructors in java.io that throw FileNotFoundException
Constructor and Description
FileInputStream(File file)
Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system.
FileInputStream(String name)
Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system.
FileOutputStream(File file)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.
FileOutputStream(String name)
Creates a file output stream to write to the file with the specified name.
FileOutputStream(String name, boolean append)
Creates a file output stream to write to the file with the specified name.
FileReader(File file)
Creates a new FileReader, given the File to read from.
FileReader(String fileName)
Creates a new FileReader, given the name of the file to read from.
PrintStream(File file)
Creates a new print stream, without automatic line flushing, with the specified file.
PrintStream(File file, String csn)
Creates a new print stream, without automatic line flushing, with the specified file and charset.
PrintStream(String fileName)
Creates a new print stream, without automatic line flushing, with the specified file name.
PrintStream(String fileName, String csn)
Creates a new print stream, without automatic line flushing, with the specified file name and charset.
PrintWriter(File file)
Creates a new PrintWriter, without automatic line flushing, with the specified file.
PrintWriter(File file, String csn)
Creates a new PrintWriter, without automatic line flushing, with the specified file and charset.
PrintWriter(String fileName)
Creates a new PrintWriter, without automatic line flushing, with the specified file name.
PrintWriter(String fileName, String csn)
Creates a new PrintWriter, without automatic line flushing, with the specified file name and charset.

  • java.io.NotSerializableException (subClass of IOException): Thrown when an instance is required to have a Serializable interface. The serialization runtime or the class of the instance can throw this exception. The argument should be the name of the class.
  • java.sql.SQLException
  • java.util.concurrent.TimeoutException
  • java.util.concurrent.ExcecutionException
  • java.lang.InterruptedException

OCPJP>cat CheckedExceptionDemo.java 
import java.text.*;
import java.util.Locale;
import java.io.*;
import java.sql.*;
public class CheckedExceptionDemo {
    public static void main(String...args) {
        try {
            Number number = NumberFormat.getInstance(Locale.FRANCE).parse("123.99");
            System.out.println("NumberFormat.parse: " + number);
            NumberFormat.getCurrencyInstance().parse("%dollar");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        
        try (FileReader fin = new FileReader("CheckedExceptionDemo.java"); BufferedReader buf = new BufferedReader(fin);) {
            try {
                System.out.println(buf.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
            new FileReader("noSuchFile");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        
        String url = "jdbc:mysql:prov";
        try (Connection conn = DriverManager.getConnection(url); 
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("select name from Member")) {
            while(rs.next()) {
                System.out.println(rs.getString(1));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
OCPJP>
OCPJP>
OCPJP>javac CheckedExceptionDemo.java 
OCPJP>java CheckedExceptionDemo
NumberFormat.parse: 123
java.text.ParseException: Unparseable number: "%dollar"
at java.text.NumberFormat.parse(NumberFormat.java:385)
at CheckedExceptionDemo.main(CheckedExceptionDemo.java:10)
import java.text.*;
java.io.FileNotFoundException: noSuchFile (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at java.io.FileReader.<init>(FileReader.java:58)
at CheckedExceptionDemo.main(CheckedExceptionDemo.java:21)
java.sql.SQLException: No suitable driver found for jdbc:mysql:prov
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at CheckedExceptionDemo.main(CheckedExceptionDemo.java:29)
OCPJP>

More runtime exceptions:


  • java.lang.ArrayStoreException
  • java.time.DateTimeException
  • java.util.MissingResourceException
  • java.lang.UnsupportedOperationException
  • java.lang.IllegalStateException

    java.util.FormatterClosedException extents IllegalStateException
    java.util.concurrent.CancellationException extends IllegalStateException
  • java.util.ConcurrentModificationException

OCPJP>cat RuntimeExceptionDemo.java 
import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.*;

public class RuntimeExceptionDemo {
    public static void main(String...args) {
        try {
            arrayStoreExceptionDemo();
        } catch (ArrayStoreException e) {
            e.printStackTrace();
        }
        
        try {
            dateTimeExceptionDemo();
        } catch (DateTimeException e) {
            e.printStackTrace();
        }
        
        try {
            missingResourceExceptionDemo();
        } catch (MissingResourceException e) {
            e.printStackTrace();
        }
        
        try {
            unSupportedOperationDemo();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        }
        
        try {
            illegalStateExceptionDemo();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        
        try {
            concurrentModificationExceptionDemo();
        } catch (ConcurrentModificationException e) {
            e.printStackTrace();
        }
    }
    
    private static void arrayStoreExceptionDemo() {
        Long[] longs = {new Long(1L), new Long(2L)};
        Object[] objs = longs;
        objs[0] = 1.3;
    }
    
    private static void dateTimeExceptionDemo() {
        LocalDateTime.of(2000, 400, 1, 1, 1);
    }
    
    private static void missingResourceExceptionDemo() {
        ResourceBundle.getBundle("nosuchName", new Locale("nosuchlang", "nosuchcountry"));
    }
    
    private static void unSupportedOperationDemo() {
        List<? extends String> l = new java.util.ArrayList<>();
        l.add(null);
        List<String> list = Arrays.asList("a", "b");
        list.add("c");
        list.remove(1);
    }
    
    private static void illegalStateExceptionDemo() {
        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<?> result = service.submit(() -> {for(int i = 0; i < Integer.MAX_VALUE; i++ ){}});
        service.shutdownNow();
        result.cancel(true);
        try {
            result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
    
    private static void concurrentModificationExceptionDemo() {
        Map<String, String> map = new HashMap<>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        for(String key : map.keySet()) {
            map.remove(key);
        }
    }
}
OCPJP>
OCPJP>
OCPJP>
OCPJP>javac RuntimeExceptionDemo.java 
OCPJP>java RuntimeExceptionDemo
java.lang.ArrayStoreException: java.lang.Double
at RuntimeExceptionDemo.arrayStoreExceptionDemo(RuntimeExceptionDemo.java:55)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:16)
java.time.DateTimeException: Invalid value for MonthOfYear (valid values 1 - 12): 400
at java.time.temporal.ValueRange.checkValidValue(ValueRange.java:311)
at java.time.temporal.ChronoField.checkValidValue(ChronoField.java:703)
at java.time.LocalDate.of(LocalDate.java:267)
at java.time.LocalDateTime.of(LocalDateTime.java:311)
at RuntimeExceptionDemo.dateTimeExceptionDemo(RuntimeExceptionDemo.java:59)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:22)
java.util.MissingResourceException: Can't find bundle for base name nosuchName, locale nosuchlang_NOSUCHCOUNTRY
at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1564)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1387)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:845)
at RuntimeExceptionDemo.missingResourceExceptionDemo(RuntimeExceptionDemo.java:63)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:28)
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:148)
at java.util.AbstractList.add(AbstractList.java:108)
at RuntimeExceptionDemo.unSupportedOperationDemo(RuntimeExceptionDemo.java:70)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:34)
java.util.concurrent.CancellationException
at java.util.concurrent.FutureTask.report(FutureTask.java:121)
at java.util.concurrent.FutureTask.get(FutureTask.java:192)
at RuntimeExceptionDemo.illegalStateExceptionDemo(RuntimeExceptionDemo.java:80)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:40)
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
at RuntimeExceptionDemo.concurrentModificationExceptionDemo(RuntimeExceptionDemo.java:92)
at RuntimeExceptionDemo.main(RuntimeExceptionDemo.java:46)
OCPJP>


Exceptions are good place for the examiner to set traps during the test. There are other Exceptions we didn't cover here, but we have to end this topic here, otherwise this topic will be too long.