Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Scala | Finally Exceptions
Next article icon

Scala | Exception Handling

Last Updated : 15 Nov, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

What is an Exception?

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. These are situations that are not too dangerous and can be handled by the program.

Exception Hierarchy

All exception and errors types are sub classes of class Throwable, which is base class of hierarchy. One branch is headed by Exception. This class is used for exceptional conditions that user programs should catch. NullPointerException is an example of such an exception. Another branch, Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-time environment itself(JRE). StackOverflowError is an example of such an error. Exception Hierarchy

Exceptions in Scala

Exception handling in Scala is implemented differently, but it behaves exactly like Java and works seamlessly with existing Java libraries. In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception. Note: At compile time “checked” exceptions are checked In Java . If a method might throw an IOException, we must declare it.

How does Scala Exception Work?

Exceptions in scala work the same way as in C++ or Java. When an exception occurs, say an ArithmeticException as shown in the previous example the current operation is aborted, and the runtime system looks for an exception handler that can accept an ArithmeticException. Control resumes with the innermost such handler. If no such handler exists, the program terminates. The Throwing Exceptions Throwing an exception. It looks same as in Java. we create an exception object and then we throw it by using throw keyword. Syntax:
throw new ArithmeticException
The try/catch Construct The try/catch construct is different in Scala than in Java, try/catch in Scala is an expression. The exception in Scala and that results in a value can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression. Here is an example of exception Handling using the conventional try-catch block in Scala. Scala
// Scala program of try-catch Exception  import java.io.IOException  // Creating object object GFG {       // Main method     def main(args:Array[String])     {           try         {             var N = 5/0                       }          catch          {             // Catch block contain cases.              case i: IOException =>              {                 println("IOException occurred.")             }             case a : ArithmeticException =>              {                 println("Arithmetic Exception occurred.")             }           }       }   }   
Output:
Arithmetic Exception occurred.
In Scala a single catch block can handle all kinds of exceptions thus providing flexibility. The finally Clause : If we want some part of our code to execute irrespective of how the expression terminates we can use a finally block. Here is an example of the above: Scala
// Scala program of finally Exception   // Creating object object GFG  {     // Main method     def main(args: Array[String])      {         try         {             var N = 5/0         }          catch         {             // Catch block contain case.             case ex: ArithmeticException =>              {                 println("Arithmetic Exception occurred.")             }         }         finally         {             // Finally block will execute              println("This is final block.")         }     } } 
Output:
Arithmetic Exception occurred.  This is final block.

Next Article
Scala | Finally Exceptions

K

Kaustav kumar Chanda
Improve
Article Tags :
  • Scala

Similar Reads

  • Exception handling in Julia
    Any unexpected condition that occurs during the normal program execution is called an Exception. Exception Handling in Julia is the mechanism to overcome this situation by chalking out an alternative path to continue normal program execution. If exceptions are left unhandled, the program terminates
    6 min read
  • Scala | Finally Exceptions
    Scala finally block is used to execute important code such as closing connection, stream or releasing resources( it can be file, network connection, database connection etc). It will be always executed not matter if an exception is thrown or not. The finally block will be executed after the try and
    3 min read
  • Spring MVC - Exception Handling
    Prerequisites: Spring MVC When something goes wrong with your application, the server displays an exception page defining the type of exception, the server-generated exception page is not user-friendly. Spring MVC provides exception handling for your web application to make sure you are sending your
    6 min read
  • Exception Handling in Programming
    Exception handling is a critical aspect of programming, enabling developers to manage unexpected or erroneous situations gracefully. In this article, we'll discuss the concept of exception handling, its importance, and best practices for implementing it effectively in various programming languages.
    7 min read
  • Exception handling in Objective-C
    Exception handling is an essential aspect of Objective-C programming, enabling developers to manage unforeseen errors effectively. Objective-C provides a robust set of tools and methodologies to handle exceptions, ensuring the stability and reliability of applications. Let's delve deeper into the nu
    5 min read
  • File Handling in Scala
    File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we don’t have a class to write into a file, in the Scala standard library. We coul
    3 min read
  • Define Exception handling in ES6
    Exception: Exceptions are unwanted event that basically interrupts the normal flow of program. There are two types of exception in general:- Synchronous (eg. runtime errors)Asynchronous (eg. system errors) Exception Handling: Often a times exception happens in a program that causes the program to te
    3 min read
  • Exception Handling in Kotlin Coroutines
    Coroutines are a new way for us to do asynchronous programming in Kotlin in Android. When developing a production-ready app, we want to ensure that all exceptions are handled correctly so that users have a pleasant experience while using our app. In this article, we will discuss how to properly hand
    7 min read
  • Exception Handling in Distributed Systems
    Exception handling in distributed systems is crucial for maintaining reliability and resilience. This article explores strategies for managing errors across networked services, addressing challenges like fault tolerance, error detection, and recovery, to ensure seamless and robust system operation.
    12 min read
  • Error Handling in MATLAB
    Error Handling is the approach of creating a program that handles the exceptions thrown by different conditions without crashing the program. For example, consider the case when you are multiplying two matrices of orders (m x n) and (m x n). Now, anyone who has done elementary linear algebra knows t
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences