Created: 2023-09-06 18:05
Status: #concept
Subject: Programming
Tags: Java Java Class java.lang Error Handling
Java Exception
They are a
Throwable
class that have many subclasses which denote different error types in the Java runtime.
Handling Errors with try-catch
When an exception is thrown inside the
try { ... }
block, the catch(Exception e)
block is executed.
- there are useful methods like
e.getMessage()
,e.printStackTrace()
, etc.
Scanner reader = new Scanner(System.in);
System.out.print("Give a number: ");
int readNumber = -1;
try {
readNumber = Integer.parseInt(reader.nextLine());
} catch (Exception e) {
System.out.println("User input was not a number.");
}
Give a number: no!
User input was not a number.
Shifting Responsibility
We can make methods
throws Exception
which signals the programmer to handle the method call's exception when used or handle it somewhere else.
public List<String> readLines(String fileName) throws Exception {
ArrayList<String> lines = new ArrayList<>();
Files.lines(Paths.get(fileName)).forEach(line -> lines.add(line));
return lines;
}
Throwing Custom Errors
Similar to JavaScript, we can
throw new ExceptionType();
to force an exception.
public class Program {
public static void main(String[] args) throws Exception {
throw new NumberFormatException(); // Program throws an exception
}
}
Common ___Exception
Types
NumberFormatException
is thrown if the string it has been given cannot be parsed into an integer.
int readNumber = Integer.parseInt("pog");
// **Exception in thread "..." java.lang.NumberFormatException: For input string: "dinosaur"**
IOException
&FileNotFoundException
is thrown when we try to java.nio.file.Paths.get("nonexistent.txt")
and it doesn't exist.
ArrayList<String> lines = new ArrayList<>();
// create a Scanner object for reading files
try (Scanner reader = new Scanner(new File("file.txt"))) {
// read all lines from a file
while (reader.hasNextLine()) {
lines.add(reader.nextLine());
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
// do something with the lines
-
IllegalArgumentException(String msg)
can be manually thrown with a message, typically used to validate bad function arguments.- we do not need to manually handle this because it stops the program automatically.
-
ArrayIndexOutOfBoundsException
when we try to index an array outside its bounds. -
InterruptedException
occurs when we useThread.sleep(ms)
in a Java Thread orRunnable
'spublic void run()
method.- it means the Thread stopped early or the class method
ThreadInstance.interrupt()
was called.
- it means the Thread stopped early or the class method