CodeGym /Courses /New Java Syntax /Exception types

Exception types

New Java Syntax
Level 15 , Lesson 4
Available
Exception types

"I wanted to talk about one more thing today. In Java, all exceptions are divided into two types: checked and unchecked (those that must be caught and those you don't have to catch). By default, all exceptions need to be caught."

"Can you intentionally throw exceptions in your code?"

"You can throw any exception in your own code. You can even write your own exceptions. But we'll talk about that later. Right now, let's concentrate on exceptions thrown by the Java Machine."

"OK."

"If ClassNotFoundException or FileNotFoundException are thrown (occur) in a method, the developer must indicate them in the method declaration. These are checked exceptions. This is how it usually looks:"

Examples of checked exceptions
public static void method1() throws ClassNotFoundException, FileNotFoundException

public static void main() throws IOException
public static void main() // Doesn't throw any exceptions

"So we just write 'throws' followed by a comma-delimited list of exceptions, right?"

"Yes. But there's more. For the program to compile, the method that calls method1 in the example below must do one of two things: either catch these exceptions or rethrow them (to the caller), indicating the rethrown exceptions in its declaration."

"Again. If your main method needs to call a method whose declaration contains 'throws FileNotFoundException, …', then you need to do one of two things:

1) Catch FileNotFoundException, …

You must wrap the code calling the unsafe method in a try-catch block.

2) Don't catch FileNotFoundException, …

You must add these exceptions to the throws list of your main method."

"Could you give me an example?"

"Take a look at this:"

Examples of checked exceptions
public static void main(String[] args)
{
    method1();
}

public static void method1() throws FileNotFoundException, ClassNotFoundException
{
    //Throws FileNotFoundException if the file doesn't exist
    FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}

"The code in this example won't compile, because the main method calls method1(), which throws exceptions that have to be caught."

"To make it compile, we need to add exception handling to the main method. You can do this in one of two ways:"

Option 1: We simply rethrow the exception (to the caller):
public static void main(String[] args)  throws FileNotFoundException, ClassNotFoundException 
{
    method1();
}

public static void method1() throws FileNotFoundException, ClassNotFoundException
{
    //Throws FileNotFoundException if the file doesn't exist
    FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}

"And here we catch it with a try-catch:"

Option 2: Catch the exception:
public static void main(String[] args)
{
    try
    {
        method1();
    }
    catch(Exception e)
    {
    }
}

public static void method1() throws FileNotFoundException, ClassNotFoundException
{
    //Throws FileNotFoundException if the file doesn't exist
    FileInputStream fis = new FileInputStream("C2:\badFileName.txt");
}

"It's starting to get clearer."

"Look at the following example. It will help you understand the rest."

Instead of handling exceptions, we rethrow them to methods farther down the call stack who know how to handle them:
public static void method2() throws FileNotFoundException, ClassNotFoundException
{
    method1();
}
Handle one exception and throw another:
public static void method3() throws ClassNotFoundException
{
   try
    {
        method1();
    }
    catch (FileNotFoundException e)
    {
        System.out.println("FileNotFoundException has been caught.");
    }
}
Catch both exceptions, throw none:
public static void method4()
{
    try
    {
        method1();
    }
    catch (FileNotFoundException e)
    {
        System.out.println("FileNotFoundException has been caught.");
    }
    catch (ClassNotFoundException e)
    {
        System.out.println("ClassNotFoundException has been caught.");
    }
}

"There is one more type of exception, the RuntimeException and classes that inherit it. You don't need to catch them. These are unchecked exceptions. They are considered difficult to predict. You can deal with them in the same way, but you don't need to indicate them in a throws clause."

Comments (11)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
AmirMasoud Level 26, Seattle, United States
24 January 2022
I can't figure out one thing if we throw our exceptions in the main method who would catch them? is there a method that calls the main method that catches exceptions? Or should we catch all of the exceptions in the main because it's the last method in stack call?
Jonaskinny Level 25, Redondo Beach, United States
20 February 2022
You should attempt to catch all exceptions as closely to where they are originally thrown as possible. You can Catch Exception (which will catch all Exceptions) in main, but assuming you can not handle them at that point, you would want to do something like System.exit(-1) <-- indicates failed processing. If you don't catch an exception in main, it goes to the caller's space (like the output in the case of calling main from an IDE, or a bootstrap class's process space, etc.
Aldo Luna Bueno Level 1, Peru
23 December 2021
The exception handling looks a lot like the lightning redirection technique in Avatar if you think about it. When you absorb lightning, you can throw it into the sky (like when using "throws" in the top method) or at a target (like when using the "try-catch" mechanism). But, if you don't redirect it, it hurts your body and it's game over (like when the program doesn't compile because you didn't catch an exception that was supposed to be caught).
Angel Li Level 18, Fremont, United States
23 June 2020
Anyone else notice the typo in the first image at the top when it says 'IndexOutOfBoundsEexception' ?🤣 The pictures helped me understand it more. Thanks CodeGym!
Vahan Level 41, Tbilisi, Georgia
31 July 2019
Can we catch exceptions in the method itself instead of method that calls it?
Corina Bodea Level 14, Cluj Napoca, Romania
6 April 2020
Right. A method can handle exception by catching it or declaring it for the caller to deal with.
Jen P Level 26
21 July 2019
What is the "runtime" errors exactly ? Can we understand that as any exceptions that pass the compilation, but leads to program terminates?
Corina Bodea Level 14, Cluj Napoca, Romania
6 April 2020
All exceptions (checked or unchecked) occur at the time that the program is run. Both are basically compiler errors. The only difference is that runtime exceptions are unchecked during compile time. They are not anticipated. For example accessing an invalid array index. It's unexpected.
// Java Poser Level 18, Cincinnati, United States
26 March 2019
I wish there was an explanation regarding the web map at the top of the page
David J. Malan Level 19, Bishkek, Kyrgyzstan
3 April 2019
Links from the Professor – 9. It will be explained in lecture number 9.
Hashirama Level 26, Port-Harcourt, Nigeria
26 January 2019
Cool!!!