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

0% found this document useful (0 votes)
6 views21 pages

Exception Handling JAVA

The document discusses exception handling in Java, outlining three types of errors: compile-time errors, logical errors, and runtime errors (exceptions). It explains the differences between checked and unchecked exceptions, the use of try-catch blocks, and the importance of the finally block for cleanup operations. Additionally, it covers the creation of user-defined exceptions and the significance of handling exceptions to maintain the normal flow of a program.

Uploaded by

Dipali Gangarde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Exception Handling JAVA

The document discusses exception handling in Java, outlining three types of errors: compile-time errors, logical errors, and runtime errors (exceptions). It explains the differences between checked and unchecked exceptions, the use of try-catch blocks, and the importance of the finally block for cleanup operations. Additionally, it covers the creation of user-defined exceptions and the significance of handling exceptions to maintain the normal flow of a program.

Uploaded by

Dipali Gangarde
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Exception Handling

In java three types of errors that can occur during the execution of a program
i) compile time error
ii)logical error
iii) run time error -- this can be called as Exception
Compile-time errors:
Compile-time errors are errors that occur during the compilation of the Java code.
These errors are caused by syntax errors, missing semicolons, or incorrect variable names,
among other things. If there are compile-time errors in your Java program, it cannot be
compiled into bytecode,
and it cannot be executed.

Logical errors:
Logical errors are errors that occur when the program runs correctly, but it does not produce
the expected output.
These errors occur because of a mistake in the program's logic. For example, if a program is
supposed to add two numbers
but instead multiplies them, it will produce the wrong output. Logical errors are more
difficult to detect than compile-time
errors because the program runs without any error messages.

Exceptions (Runtime error)


Exceptions are errors that occur during the execution of the Java program.
Exceptions occur when something unexpected happens, such as trying to read from a file
that does not exist or dividing by zero.
When an exception occurs, the program will terminate unless the exception is handled by an
exception handler.

Important:
both checked and unchecked exceptions can occur during runtime, but checked exceptions
are checked at compile time and require handling or declaring, while unchecked exceptions
are not checked at compile time and do not require handling or declaring.
Exception handling in Java allows developers to manage runtime errors effectively by using
mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc.

An Exception is an unwanted or unexpected event that occurs during the execution of a program
(i.e., at runtime) and disrupts the normal flow of the program’s instructions.

It occurs when something unexpected happens, like accessing an invalid index, dividing by zero, or
trying to open a file that does not exist.
Note: With the help of exception handling we can detect and handle the exceptions gracefully so that
the normal flow of the program can be maintained.

Note: The finally block always executes, even if no exception occurs, making it a reliable place for
cleanup operations.
Exception occurs due to our programs.

Exceptions are recoverable.

Errors occur bcoz of lack of system resources. (not by program, thus user cannot do anything)

Errors are not recoverable.


If we did not use try catch block then jvm directly use default exception handler to hadle exception if
occurs
Checked vs Unchecked Exceptions
• Checked - These exceptions are checked at compile time, forcing the programmer to
handle them explicitly.
• Unchecked - These exceptions are checked at runtime and do not require explicit
handling at compile time.

For checked exception, you must have to use try catch or throws keyword

ANALOGY FOR Checked and unchecked exception –


Imagine a mother (compiler) checking on her son before he leaves for work (running the
program). She makes sure he has everything he needs—his purse, lunch, and work
documents. If anything is missing, she stops him right there and asks him to fix it before
leaving.

This is like a Checked Exception in Java—errors that must be handled before the program
runs. If something important is missing, the compiler won’t let you proceed until it’s fixed.
Now, once the son leaves the house, the mother can’t control what happens. Maybe his bike
gets a flat tire, he gets stuck in traffic, or he meets with an accident. These are unexpected
problems that she couldn’t check beforehand.

This is like an Unchecked Exception in Java—errors that happen unexpectedly while the
program is running. The compiler won’t warn you, but you might face issues during
execution.
So in short:
• Checked exceptions are like a mother checking everything before her son leaves
(compiler forcing you to handle certain errors).
• Unchecked exceptions are like unexpected problems on the road (errors that happen
at runtime and the compiler doesn’t check them).

Examples –

1.
2.

In below fig, first two are checked exception. And next 2 are unchecked exception.
in checked, it will give exception during compiling only (javac abc.java). it will not compile.
In unchecked program will get compiled successfully, but it will give exception error in runtime (java
test).

So we need to handle checked excpetion. We need not to handle unchecked exception

TRY CATCH –
Internal working of Try-Catch Block
• Java Virtual Machine starts executing the code inside the try block.
• If an exception occurs, the remaining code in the try block is skipped, and
the JVM starts looking for the matching catch block.
• If a matching catch block is found, the code in that block is executed.
• After the catch block, control moves to the finally block (if present).
• If no matching catch block is found the exception is passed to the JVM default
exception handler.
• The final block is executed after the try catch block. regardless of weather an
exception occurs or not.
Methods to Print Exception Information in Java -
e.printStackTrace() – prints all exception name, description, stack trace
sout€ or sout(e.toString()) - – prints exception name, description
sout(e.getMessage()) – prints only description
Why finally block is used?? → for cleanup
→ we can take eg of we are opening a file in try, then we are reading / writing in it. At time
time of reading / writing if exception occur, then it will directly moves to catch and finally
block. Now we need to close that file, for that there should be some method in which we
can write that code to close, so that we need finally block as it runs always whether
exception occur or not.
finally Keyword
This keyword in Java is used to create a block of code that always executes after
the try block, regardless of whether an exception occurs or not.
Used for writing clean up code.
If any resourse is opened in try then it will be closed in finally
We can use multiple catch blocks with one try block. But we can only use single finally block
with each try block

Jis method mai exception create karne wala code likha hai, vahi method exception object
create karega
In above image,
Left part → main method will create exception object and then that object is passed to jvm
Right part → user will directly create exception object and it is passed to jvm

Throw keyword mainly used for custom exception (user defined exception)
Still the program terminates abnormally if age is < 18. To run program succesffully , with
exception handling, we have to use try catch

In above method also, exception handling is not done, it gets terminates if age < 18.
Throw -→
In this above img, readfile method simply tells main that (in which that function is called)
that you have to keep in mind that this function may throw an exception which you (main )
need to handled. Object of exception is created by main method. So that we have to use try
catch in main method

Throws keyword kabhi bhi exception handle nahi karta. Vo sirf batata hai ki vo kis type ka
exception create kar sakta hai
User-Defined Custom Exception in Java
User-Defined Custom Exception or custom exception is creating your own
exception class and throwing that exception using the ‘throw’ keyword.
Create a User-Defined Custom Exception
1. Create a new class that extends Exception (for checked exceptions) or
RuntimeException (for unchecked exceptions).
2. Provide constructors to initialize the exception with custom messages.
3. Add methods to provide additional details about the exception. (this is
optional)

You might also like