Try-Catch Block

Start course
Overview
Difficulty
Beginner
Duration
50m
Students
24
Description

In this course, we'll learn about Exception Handling in Java.

Learning Objectives

  • What is an Exception?
  • Difference between Error and Exception
  • Types of Exceptions
  • Try-Catch Block
  • Finally Block
  • Throw and Throws Keywords
  • Exception Methods

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams

Prerequisites

  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge
Transcript

Hi there. In this video, we will learn about the Try-Catch Block. So, what is the try-catch block in Java?

If we want to handle the exception ourselves, we can use a try-catch block. In Java, the try block is used to enclose the code that may throw an exception. A try block consists of a set of executable statements. During the execution of these statements, exceptions can be thrown. A method that may throw an exception can also be enclosed by the try block. A try block is always followed by a catch block. We handle the exception in the catch block. One or more catch blocks can follow a try block. In the catch block, we use the exception object to print details of the exception. As you can see in the diagram, first, the try block is executed. If the code in the try block throws an exception, the catch block is executed. 

Okay, now let's look at the usage of multiple catch blocks. We use multiple catch blocks after the try block. A try block maybe followed by any number of catch blocks. Each catch block handles a particular type of exception. Before Java 7, we used to catch multiple exceptions, one by one as shown in the slide. With Java 7, if a catch block handles multiple exceptions, we can separate them using a pipe and in this case the exception parameter is final, so we can't change it. This feature reduces code redundancy. Yes, the try-catch block in Java is like that. Let's take a short break here. In the next video, we'll talk about the Finally block. See you in the next video.

 

About the Author
Students
458
Courses
47
Learning Paths
3

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics