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());
}
}
}
Create your own kind of Exception (use inheritance). Set the value of message by super in a constructor.
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());
}
}
}
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]);
}
}
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");
}
}
}
Create a program, that calculates total of numbers located in a given file.
Create a program, that reads itself.
Create a program, that reads a Java source file (.java) and displays list of Java keywords with number of occurrences.