Thanks to visit codestin.com
Credit goes to www.w3schools.com

Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Advanced Sorting

Java Projects

Java Projects

Java How To's

Java How Tos Add Two Numbers Swap Two Variables Even or Odd Number Reverse a Number Positive or Negative Square Root Area of Rectangle Celsius to Fahrenheit Sum of Digits Check Armstrong Number Random Number Count Words Count Vowels in a String Remove Vowels from String Count Digits in a String Reverse a String Palindrome Check Check Anagram Convert String to Array Remove Whitespace Count Character Frequency Sum of Array Elements Find Array Average Sort an Array Find Smallest Element Find Largest Element Second Largest Array Min and Max Array Merge Two Arrays Remove Duplicates Find Duplicates Shuffle an Array Factorial of a Number Fibonacci Sequence Find GCD Check Prime Number ArrayList Loop HashMap Loop Loop Through an Enum

Java Reference

Java Reference Java Keywords Java String Methods Java Math Methods Java Output Methods Java Arrays Methods Java ArrayList Methods Java LinkedList Methods Java HashMap Methods Java Scanner Methods Java File Methods Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter Java Iterator Methods Java Collections Methods Java System Methods Java Errors & Exceptions

Java Examples

Java Examples Java Compiler Java Exercises Java Quiz Java Server Java Syllabus Java Study Plan Java Certificate


Java Exceptions - Try...Catch


Java Exceptions

As mentioned in the Errors chapter, different types of errors can occur while running a program - such as coding mistakes, invalid input, or unexpected situations.

When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).


Exception Handling (try and catch)

Exception handling lets you catch and handle errors during runtime - so your program doesn't crash.

It uses different keywords:

The try statement allows you to define a block of code to be tested for errors while it is being executed.

The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

The try and catch keywords come in pairs:

Syntax

try {
  //  Block of code to try
}
catch(Exception e) {
  //  Block of code to handle errors
}

Consider the following example:

This will generate an error, because myNumbers[10] does not exist.

public class Main {
  public static void main(String[ ] args) {
    int[] myNumbers = {1, 2, 3};
    System.out.println(myNumbers[10]); // error!
  }
}

The output will be something like this:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
        at Main.main(Main.java:4)

Note: ArrayIndexOutOfBoundsException occurs when you try to access an index number that does not exist.

Try it Yourself »

If an error occurs, we can use try...catch to catch the error and execute some code to handle it:

Example

public class Main {
  public static void main(String[ ] args) {
    try {
      int[] myNumbers = {1, 2, 3};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong.");
    }
  }
}

The output will be:

Something went wrong.
Try it Yourself »

Finally

The finally statement lets you execute code, after try...catch, regardless of the result:

Example

public class Main {
  public static void main(String[] args) {
    try {
      int[] myNumbers = {1, 2, 3};
      System.out.println(myNumbers[10]);
    } catch (Exception e) {
      System.out.println("Something went wrong.");
    } finally {
      System.out.println("The 'try catch' is finished.");
    }
  }
}

The output will be:

Something went wrong.
The 'try catch' is finished.
Try it Yourself »


The throw keyword

The throw statement allows you to create a custom error.

The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print "Access granted":

public class Main {
  static void checkAge(int age) {
    if (age < 18) {
      throw new ArithmeticException("Access denied - You must be at least 18 years old.");
    }
    else {
      System.out.println("Access granted - You are old enough!");
    }
  }

  public static void main(String[] args) {
    checkAge(15); // Set age to 15 (which is below 18...)
  }
}

The output will be:

Exception in thread "main" java.lang.ArithmeticException: Access denied - You must be at least 18 years old.
        at Main.checkAge(Main.java:4)
        at Main.main(Main.java:12)
Try it Yourself »

If age was 20, you would not get an exception:

Example

checkAge(20);

The output will be:

Access granted - You are old enough!
Try it Yourself »

Errors and Exception Types

The table below shows some of the most common errors and exceptions in Java, with a short description of each:

Error/Exception Description
ArithmeticError Occurs when a numeric calculation goes wrong
ArrayIndexOutOfBoundsException Occurs when trying to access an index number that does not exist in an array
ClassNotFoundException Occurs when trying to access a class that does not exist
FileNotFoundException Occurs when a file cannot be accessed
InputMismatchException Occurs when entering wrong input (e.g. text in a numerical input)
IOException Occurs when an input or output operation fails
NullPointerException Occurs when trying to access an object referece that is null
NumberFormatException Occurs when it is not possible to convert a specified string to a numeric type
StringIndexOutOfBoundsException Occurs when trying to access a character in a String that does not exist

Tip: For a list of all errors and exception types, go to our Java Errors and Exception Types Reference.




×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.