Exceptionu print etməyin əsas 3 yolu var:
public static void main(String[] args) {
try {
hop();
} catch (Exception e) {
System.out.println(e); // first way
System.out.println(e.getMessage()); // second way
e.printStackTrace(); // third way
}
}
private static void hop() {
throw new RuntimeException("can not hop");
}
Output:
java.lang.RuntimeException: can not hop // first way
can not hop // second way
java.lang.RuntimeException: can not hop // third way
at chapter6.PrintingException.hop(Handling.java:17)
at chapter6.PrintingException.main(Handling.java:9)
Praktikada həmişə catch blokunda exceptionla bağlı bildirişin çap edilməsi məsləhət görülür. Nümunə üçün aşağıdakı koda baxaq:
import java.io.IOException;
class ExceptionMessage {
public static void main(String[] args) {
String textInFile = null;
try {
readInFile();
} catch (IOException e) {
// ignore exception message
}
// many lines of code
System.out.println(textInFile.replace(" ", ""));
}
private static void readInFile() throws IOException {
throw new IOException();
}
}
Bu kodu çalışdırsaq NullPointerException verəcək, amma IOException`un baş verməsi ilə bağlı heç bir xəbərimiz olmayacaq.
[topics lang=az]
