Back to all lessons


Lesson 14

Exceptions and IO

Task 0

Throw an exception with your message. Tip: look at the constructor of Exception class.


public class Main {
    public static void main(String[] args) {
        try {
            throw new Exception();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
            
Task 1

Create your own kind of Exception (use inheritance). Set the value of message by super in a constructor.

Task 2

Throw your own Exception in a method.


public class Main {
    public static void main(String[] args) {
        try {
            throwCustomException();
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }
}
            
Task 3

Execute the code written below. What kind of Exception do you see? Handle an error using try-catch statement.


public class Main {
    public static void main(String[] args) {
        int[] arr = new int[2];
        System.out.println(arr[2]);
    }
}
            
Task 4

Create a class called PositiveNumberOnly, which takes double as an parameter in constructor and throws ItIsNotPositiveNumberException, if the parameter's value is below 0.

How to read a file in Java?


import java.io.FileInputStream;

public class Main {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("file.txt");
            StringBuilder sb = new StringBuilder();
            int c;
            while ((c = fis.read()) != -1) {
                sb.append((char)c);
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            System.out.println("Error: file reading failed");
        }
    }
}
    
Task 5

Create a program, that calculates total of numbers located in a given file.

Task 6

Create a program, that reads itself.

Task 7

Create a program, that reads a Java source file (.java) and displays list of Java keywords with number of occurrences.