India: +91-4446 311 234 US: +1-6502 652 492 Whatsapp: +91-7530 088 009
Upto 20% Scholarship On Live Online Classes

 

what is Exception handling  in java?

Exception handling is the process of responding to an error in code. Java provides a mechanism for detecting errors during runtime and recovering from them without crashing the program.

 

There is nothing special about a “try/catch” block in Java; any block of code surrounded by curly braces is a try/catch block. In fact, it is just a shorthand for surrounding every instruction in the block with try and catch blocks.

try and catch block in java

That’s not to say there is nothing “special” about them, though. A try/catch block is used when something in your program crashes, and you want to make sure it is written out.

Try

{

// code that could fail

}

catch(Exception e)

{

// if it fails, just log the error and then exit

System.err.println(“Exception happened!”);

System.exit(-1);

}

In fact, the code above is one of the few cases where catch blocks actually need to be placed in curly braces; putting them after a block without any braces will lead to very confusing code.

You will see lots of examples on the internet (in tutorials and books) that only have their catch block after the try block. That is really just bad practice; it makes the code hard to read, and it creates a lot of possible problems.

try { // code that could fail }
catch(Exception e)

{

// if it fails, just log the error and then exit

System.err.println(“Exception happened!”);

System.exit(-1);

}

 

You should always surround your try/catch block with curly braces, and you should always have a catch block at the end of the try bloc

online Java course with placement will help students to understand object-oriented programming in a better way. They will get an understanding of how to write a program using Java. The course also includes a session on how to debug programs written in Java

advantages of try and catch blog in java

  1.  Separating Error-Handling Code from “Regular” Code
  2. Propagating Errors Up the Call Stack
  3. Grouping and Differentiating Error Types