Java Throwable is a class that represents an error or an exceptional event that occurs in a Java program during the runtime. It is the superclass of all errors and exceptions in Java programming language. The Throwable class consists of two subclasses: Exception and Error. The Exception class is used to indicate the exceptional conditions that can be caught and handled by the program, while the Error class indicates serious problems that may not be caught or handled by the program.
Example 1: Catching an Exception
try { int num = Integer.parseInt("abc"); } catch (NumberFormatException e) { System.out.println("Input is not a number"); }
This code example catches a NumberFormatException that may occur if we try to parse a string that is not a valid number. The Exception is caught and handled by printing out a user-friendly message to the console.
Package library: java.lang
Example 2: Throwing an Exception
public int divide(int a, int b) throws ArithmeticException { if (b == 0) { throw new ArithmeticException("Cannot divide by zero"); } return a / b; }
This code example is a method that takes two numbers as input parameters and throws an ArithmeticException if the second number is zero. The Exception is thrown to indicate a mathematically invalid operation and to prevent the program from crashing.
Package library: java.lang
Example 3: Creating a Custom Exception
public class MyException extends Exception { public MyException(String message) { super(message); } }
This code example creates a custom Exception class called MyException that extends the base Exception class. It has a constructor that takes a message as an input parameter and passes it to the parent constructor using the super keyword. We can use this custom Exception class to throw and catch our own exceptions in the program.
Package library: java.lang
Java Throwable - 30 examples found. These are the top rated real world Java examples of Throwable extracted from open source projects. You can rate examples to help us improve the quality of examples.