java exceptions

public class MyCustomException extends RuntimeException { public MyCustomException(String message) { super(message); } } class Test { public static void main(String[] args) { Test test = new Test(); try { test.reserveSeats(8); } catch (MyCustomException e) { System.out.println(“Exception occurred with message: ” + e.getMessage()); } } private void reserveSeats(int numberOfSeats) { if (numberOfSeats > 5) { throw…

Read More Custom Exceptions in Java

throw new Exception(); class Test { public static void main(String[] args) { Test test = new Test(); test.reserveSeats(8); } private void reserveSeats(int numberOfSeats) { if (numberOfSeats > 5) { throw new IllegalArgumentException(“No more than 5 seats can be reserved.”); } else { System.out.println(“Reservation successful!”); } } } Output: Exception in thread “main” java.lang.IllegalArgumentException: No more…

Read More Difference Between throw and throws in Java

void methodName() throws Exception class Test { public static void main(String[] args) { } private void validateStatus(String status) { if (status.equals(“invalid”)) { throw new IOException(“Status of the file is invalid, the stream is closed!”); } } } class Test { public static void main(String[] args) { Test test = new Test(); test.validateStatus(“valid”); // OK test.validateStatus(“invalid”);…

Read More Java throws Keyword

throw new Exception(); class Test { public static void main(String[] args) { reserveSeat(new User(“Steve”, “Johnson”, false, 32)); // OK reserveSeat(new User(“Mike”, “Lawson”, true, 16)); // Exception will occur } private static void reserveSeat(User user) { if (user.getAge() < 18) { throw new IllegalArgumentException(“The user is under 18 years old!”); } } } class User {…

Read More Throw an Exception in Java

try { //Statements that may cause an exception } catch { //Handling exception } finally { //Statements to be executed } class Test { public static void main(String[] args) { try { System.out.println(20 / 0); // this will throw ArithmeticException } catch (ArithmeticException ae) { System.out.println(“ArithmeticException occurred!”); } finally { System.out.println(“Finally block…”); } } }…

Read More Java finally block

Java try-catch blocks are an essential part of Java programming, used for handling exceptions that might occur during program execution. When used correctly, try-catch blocks can help you write more robust and error-free code. In this tutorial, I will explain what Java try-catch blocks are, how they work, and how to use them effectively. I’ll…

Read More Java Try-Catch Blocks: A Comprehensive Guide